将多行脚本粘贴到 PowerShell ISE 时,它似乎会一次执行整个脚本块。
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:\>
将多行脚本粘贴到 PowerShell 控制台时,它似乎尝试逐行执行?
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:\>
我期望 PowerShell 控制台的行为与 PowerShell ISE 中的行为相同,它应该知道这else
是语句的一部分if
。
我不记得它曾经有过这样的行为。是什么导致了这种行为的不同?
答案1
您的脚本失败了,因为else {
与 不在同一条线上}
。请添加反引号以表明它正在扩展到下一行,或者删除 之前的回车符else
:
if ($true) {
Write-Output "yes"
} else {
Write-Output "no"
}