Table of Contents
else is Not Recognized as the Name of a Cmdlet
We’re writing a PowerShell script to join a client into AD. We want to print a message if the computer is joined in Domain in the else clause.
$domain = (Get-WMIObject -NameSpace "Root\Cimv2" -Class "Win32_ComputerSystem").Domain
if ($domain -eq 'WORKGROUP') {
Add-Computer -DomainName 'duybao.me' -DomainCredential $creds -Restart
}
else {
Write-Host "Already in Domain" -ForegroundColor Yellow
}
But we get the following error when running the command directly from a PowerShell console:
PS C:\> $domain = (Get-WMIObject -NameSpace “Root\Cimv2” -Class “Win32_ComputerSystem”).Domain
PS C:\> if ($domain -eq ‘WORKGROUP’) {
>> Add-Computer -DomainName ‘duybao.me’ -DomainCredential $creds -Restart
>> }
PS C:\> else {
>> Write-Host “Already in Domain” -ForegroundColor Yellow
>> }
else : The term ‘else’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ else {
+ ~~~~
+ CategoryInfo : ObjectNotFound: (else:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
That’s because when dealing with not the PowerShell Integrated Console. PowerShell just throws the text in the editor into the terminal window.
With the PowerShell Integrated Console (such as Windows PowerShell ISE), it did something differently (sending a message behind the scenes with the full script to make sure the full script gets run). We can do this because it’s Integrated.
That’s why you got the error when run at the command prompt, but when run in a script it should work fine.
To fix it, we need to change the code a little bit. PowerShell seems to consider the else block as separate statement, not attached to if. Modified the code to use the end of the if and else in the same line.
$domain = (Get-WMIObject -NameSpace "Root\Cimv2" -Class "Win32_ComputerSystem").Domain
if ($domain -eq 'WORKGROUP') {
Add-Computer -DomainName 'duybao.me' -DomainCredential $creds -Restart
} else {
Write-Host "Already in Domain" -ForegroundColor Yellow
}
As you can see, now your script can be run from command prompt without any error.
And it should be run in script mode as well.
Not a reader? Watch this related video tutorial: