Else and Elseif not recognized as the name of a cmdlet, function, script file, or operable program in win10, 2012 or 2016. 2008r2 is fine RRS feed

  • Question

  • So I am having issues with the if statement on windows server 2012, 2016 and windows 10.

    Both 2008 R2 and 2012 are at the same versions below.


    Name                           Value
    ----                           -----
    PSVersion                      5.1.14409.1012
    PSEdition                      Desktop
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    BuildVersion                   10.0.14409.1012
    CLRVersion                     4.0.30319.42000
    WSManStackVersion              3.0
    PSRemotingProtocolVersion      2.3

    I even tried to copy and paste the example in the about_if and it also fails and tells me that the elseif and else are not recognized.

    Sample used was

    $a = 4

    if ($a -gt 2)
        Write-Host "The value $a is greater than 2."
    elseif ($a -eq 2)
        Write-Host "The value $a is equal to 2."
        Write-Host "The value $a is less than 2 or was not created
    or initialized."

    It works perfectly fine on my windows 2008 R2 box. Any reasons or fix?

    • Moved by Bill_Stewart Monday, December 17, 2018 6:07 PM This is not "teach me basics step-by-step" forum
    Wednesday, September 19, 2018 6:48 PM

All replies

  • The formatting of your code makes the syntax ambiguous.  Use the following formatting style.

    $a = 4
    if($a -gt 2){
         Write-Host "The value $a is greater than 2."
    }elseif($a -eq 2){
         Write-Host "The value $a is equal to 2."
         Write-Host "The value $a is less than 2 or was not created or initialized."


    Wednesday, September 19, 2018 7:06 PM
  • That was a simple copy/paste from get-help aboutif

    So the syntax is Microsoft's own sample and does not answer the question why it works on one machine and not the others.

    Thursday, September 27, 2018 2:33 PM
  • Which is one good reason to use the style I posted.  It eliminates that ambiguity.

    If you have issues with this then the correct place to post is in UserVoice.  You will likely find that many others have already posted this issue.


    Thursday, September 27, 2018 2:37 PM
  • Also note that this issue only occurs when pasting code at a prompt.  It does not happen in the ISE prompt on any system.  This behavior happens on all systems pre-Windows 8.  All W8 and later systems, as far as I know, do not have this behavior when pasting into a prompt.


    Thursday, September 27, 2018 2:46 PM