r/PowerShell • u/Ummgh23 • Mar 31 '26
Question Best Pracise - Leave a variable created by a conditional check uninitialized or set it to $null?
Just wondering what everyone's opinion on this is. Do you prefer to null a variable or just not initialize it? I couldn't find any "official" best practise for this.
PowerShell does evaluate uninitialized variables to $null automatically, but manually assigning it might help with clarity and possibly some edge cases where not initializing it could cause an issue?
For example, if a variable exists in the caller's scope. Not nulling it would carry its value over into the current scope.
As an example:
if ($SomeCondition) {
$SomeVariable = "Condition is true"
} else {
$SomeVariable = $null
}vs.
if ($SomeCondition) {
$SomeVariable = "Condition is true"
}