Table of Contents
Debugging Visual Studio Code and manually running an if else statement erroring
If you look at the piece of code below, you would say this works.
This works, but when you run this manually in the Visual Studio Code debugger, you get the following 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.
$WhyIsElseNotWorking = $true
if ($WhyIsElseNotWorking) {
Write-Host '1'
}
else {
Write-Host '0'
}
Write-Host "It's working, but not run by hand(F8)"
When you start the debugger in Visual Studio Code (F5) and have a breakpoint somewhere, you can manually run lines, or selected lines, to see what the outcome is.

So, when this is run manually in Visual Studio Code debugger, it will error out with else
not being recognized.
if ($WhyIsElseNotWorking) {
Write-Host '1'
}
else {
Write-Host '0'
}
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.
If I’m correct, this is happening because when manually running code in the debugger, the lines are pasted line by line into the terminal.
This causes the else
statement to be seen as a separate cmdlet.
Fun thing, by creating a separate function for else, it doesn’t error out and my function is called.
function else {
Write-Host "It's working, but not run by hand(F8)"
}
$WhyIsElseNotWorking = $true
if ($WhyIsElseNotWorking) {
Write-Host '1'
}
else {
Write-Host '0'
}
It's working, but not run by hand(F8)
There is a work around for the if else statement not being recognized
I think the problem is because an if
statement also works without an else
statement.
To ensure that the else
statement is seen as a statement instead of a cmdlet or function, you will have to place it on the same line as the closing bracket of the if statement.
This way, the else
is passed along with the if
statement when applying new lines.
$WhyIsElseNotWorking = $true
if ($WhyIsElseNotWorking) {
Write-Host '1'
} else {
Write-Host '0'
}
1
Conclusion
I use default formatting tools in Visual Studio Code that puts an if else
statement on its own line. As a result, I often encounter this bug.
Because of this I have to manually make an adjustment during debugging to put the else
statement on the same line as the closing bracket.
This is not nice, but I have no other choice (without changing the default formatting).
I stick to a manual adjustment that I then format again.