Home > Net >  Powershell: 'else' is not recognized if written in a new line
Powershell: 'else' is not recognized if written in a new line

Time:10-02

When I run an if/else Construct like this in my Powershell Command line

if ($foo) {
    Write-Host "foo!"
}
else {
    Write-Host "bar!"
}

it throws an error:

else: The term 'else' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

enter image description here

But when I run it like this:

if ($foo) {
    Write-Host "foo!"
} else {
    Write-Host "bar!"
}

... it works fine!

PS> bar!

It seems, that Powershell interprets else as a standalone command. Which is wrong, of course (else always needs an if or elseif before).

Fun Fact: In Function, ForEach operations or executed as ps1. it behaves as desired.

Does anyone know how to get rid of this? This annoying behavior is on all Powershell Versions (5, 7, Core) and Platforms identical.

CodePudding user response:

Technically an if statement without an else is a valid expression so the PowerShell terminal does not know that YOU want to extend that expression to the next line with an else. And so it interprets the else as a new statement altogether, hence the error.

Of course the behaviour in a file is different as Powershell knows where the start and end of a file is so it can parse it all, instead of line by line. In this example if you want PowerShell to expect more expression then end the line with a backtick "`"

if ($foo) { # open bracket so Powershell knows to continue expecting input
    Write-Host "foo!"
} ` # end of bracket so this could potentially be the end of the expression, 
    # but with a backtick it knows to continue processing!
else {
    Write-Host "bar!"
}

CodePudding user response:

Powershell is interpreting the } as the end of the statement, so also interprets the else as the start of a new statement.

You can solve this by putting a tick ` after the } to indicate that the line should not terminate.

So,

if ($foo) {
    
    Write-Host "foo!"
} ` #notice the tick (`) which instructs powershell not to consider this the end of the current statement
else {
    Write-Host "bar!"
}
  • Related