function - 为什么不能使用PowerShell在if语句中组合变量和函数?

标签 function variables powershell if-statement

运行:

$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/

相关文章:

python - 如何将 python 事件变量传递给另一个函数?

r - 删除所有包含 "prohibited"值的观察值的函数 - R

mysql - 节约资源

powershell - 解码powershell命令进行编码

powershell.exe 选项卡完成 - 列出替代方案?

c++ - 嵌套模板 typedef - 类型定义

c++ - 无法使用 square() 函数 c++

function - Lua - 检查用户输入的表是否存在并从中读取

mysql - 渲染部分帮助和故障

node.js - 如何更改 Node 模块 "say"的音频输出设备