运行:
$a = "HelloWorld"
if ($a -and b) {Write-Host "helloworld"}
function b { return "HelloWorld"}
返回:
At C:\Users\r\Desktop\test.ps1:24 char:12
+ if ($a -and b) {Write-Host "helloworld"}
+ ~
You must provide a value expression following the '-and' operator.
At C:\Users\r\Desktop\test.ps1:24 char:13
+ if ($a -and b) {Write-Host "helloworld"}
+ ~
Unexpected token 'b' in expression or statement.
At C:\Users\r\Desktop\test.ps1:24 char:13
+ if ($a -and b) {Write-Host "helloworld"}
+ ~
Missing closing ')' after expression in 'if' statement.
At C:\Users\r\Desktop\test.ps1:24 char:14
+ if ($a -and b) {Write-Host "helloworld"}
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : ExpectedValueExpression
解决方法
if ($a) {
if (b) {
Write-Host "helloworld"
}
}
结果是:
helloworld
最佳答案
所有关于顺序。解决方法如下:
function b { return "HelloWorld"}
$a = "HelloWorld"
if ($a -and (b)) {Write-Host "helloworld"}
第一点:该功能需要在您尝试调用它时定义。如果定义在调用之后,它将失败,因为它尚不存在。
第二点:您需要先评估函数返回的值,然后再尝试与之进行比较,因此您需要在调用周围使用括号以确保在逻辑运算之前执行它。
关于function - 为什么不能使用PowerShell在if语句中组合变量和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319374/