I've come across an If($True)
statement in a script I'm working on, but I haven't been able to really tell what exactly that's doing. It seems that the script proceeds into the next block regardless, and I haven't found anything that'd cause it to NOT execute the next section (a Try/Catch statement).
Of course, I understand what it would mean if it were If($var -eq $true)
, but without the variable there for it to check I just don't understand what this is doing
Edit: Example
If($True){
Try {Write-Host "Hello World"}
Catch {"oops"}
}
vs
If($var -eq $True){
Try {Write-Host "Hello World"}
Catch {"oops"}
}
CodePudding user response:
The If($True)
statement isn't strictly necessary as it will always evaluate to True
and proceed to execute the script block. I can see why this is confusing, because it's semantically superfluous.
Basically, if the value inside the ()
evaluates to anything other than $false
, 0
, $null
, or ""
(an empty string), it will execute the script block.
Why it's written that way is probably only known to the author. If I had to guess, perhaps it is to keep the style of the code similar to other code around it. I certainly wouldn't have bothered writing it as anything other than a simple Write-Host "Hello World"
unless there was some sort of style guide mandating that format, or other reason to wrap everything in if
s and try/catch blocks.