A lot of our (existing) scripts are formatted that way (with the opening IF statement curly bracket on a new line) for readability. The other day, I wanted to add in some error trapping to an existing script and when testing, I noticed that this error was being reported (and trapped), so the script was exiting out. I assume this has been occurring for a while now and we never knew that it was until I tried to add in some error trapping stuff. Thank you both for your replies.–Jun 14 '17 at 16:57.
Jan 12, 2018 - One of those statement is the switch statement and in PowerShell. You can have much more complicated logic by using elseif and else. Mar 9, 2016 - PowerShell is definitely no different and I am going to take some time to cover the basics of PowerShell by looking at the If/Else/ElseIf.
When PowerShell is fed a line (or block) of code - it evaluates that block (or line) as a wholeIn this case, your first line is: If ($error -ne $null)PowerShell knows how to interperate the line, but its invalid syntax because PowerShell doesn't have a 'what to do' block in the event that the criteria is met.If you feed PowerShell the block as a whole - it recognises the 'what to do block' and knows where it needs to go next:Are you able to elabourate more on which systems and platforms you are finding that accept the single lines? I have just tested this on Win10 (PowerShell 5), 2012R2 (Powershell 4 and 5), Windows 7 (PowerShell 4 and 5) and they all behave exactly the same.
![Else Else](/uploads/1/2/5/4/125438769/954644268.jpg)
TipSee the sections “” and “” for a discussion on how PowerShell evaluatesexpressions as conditions.If condition evaluates to $false, then PowerShell evaluates anyfollowing (optional) elseifconditions until one matches. If one matches, PowerShell executes thestatement block associated with that condition, then resumes executionat the end of the if / elseif / else statement list.If none of the conditions evaluate to $true, then PowerShell executes thestatement block associated with the (optional) else clause, then resumes execution at theend of the if / elseif / else statement list.