簡體   English   中英

為什么不能使用PowerShell在if語句中組合變量和函數?

[英]Why can one not combine a variable and a function in an if-statement using PowerShell?

運行:

$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"}

第一點:函數需要在您嘗試調用它時定義。 如果定義在調用之后,它將失敗,因為它還不存在。

第二點:在嘗試與函數進行比較之前,需要先評估函數的返回值,因此需要在調用周圍使用括號以確保在邏輯運算之前執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM