Ao colar um script multilinha no PowerShell ISE, parece executar todo o bloco de script de uma só vez.
Saída do PowerShell ISE
PS C:\> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.145
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.145
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
PS C:\> if ($true) {
Write-Output "yes"
}
else {
Write-Output "no"
}
yes
PS C:\>
Ao colar um script de várias linhas no console do PowerShell, parece tentar executar linha por linha?
Saída do Console do PowerShell
C:\> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.18362.145
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.145
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
C:\> if ($true) {
>> Write-Output "yes"
>> } yes
C:\> else {
>> Write-Output "no"
>> } 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
C:\>
O comportamento que espero do Console do PowerShell é o mesmo do PowerShell ISE, ele deve saber que else
faz parte da if
instrução.
Não me lembro de alguma vez ter agido dessa forma. O que está fazendo com que esse comportamento seja diferente?
Responder1
Seu script está falhando porque else {
está em uma linha diferente da }
linha acima. adicione um crase para indicar que está se espalhando para a próxima linha ou remova o retorno de carro antes else
:
if ($true) {
Write-Output "yes"
} else {
Write-Output "no"
}