簡體   English   中英

包含 integer '0' 的 PowerShell 數組與“^(0|3010)$”不匹配

[英]PowerShell array containing integer '0' does not match “^(0|3010)$”

我正在嘗試使用 -match 語句處理多個安裝程序的返回代碼。 我希望以下代碼能夠兩次返回“安裝程序成功運行”-但 -match 語句不適用於包含值 0 的 integer 數組...

$InstallerExitCodes = @()

$InstallerExitCodes += 0 # Pretend this is (Start-Process -PassThru -Wait installer.exe).ExitCode which returns 0 (success)

If ($InstallerExitCodes -match "^(0|3010)$") {
    Write-Output "Installer(s) ran successfully" # This does not run
}

$InstallerExitCodes += 3010 # Pretend this is (Start-Process -PassThru -Wait installer.exe).ExitCode which returns 3010 (success with reboot required)

If ($InstallerExitCodes -match "^(0|3010)$") {
    Write-Output "Installer(s) ran successfully" # This does
}

它肯定匹配0 - 問題不是正則表達式比較,而是if語句。

PowerShell 的標量比較運算符有 2 種操作模式

  • 標量模式:當左側操作數不可枚舉時,如1 -eq 1 , PowerShell 返回比較的 boolean 結果 - 也就是說,表達式的計算結果為$true$false
  • 過濾模式:當左側運算符枚舉時,比較運算符的作用類似於過濾器1,2,3 -gt 1不返回$true$false ,它返回由項目23組成的數組,因為他們滿足約束-gt 1

由於$InstallerExitCodes被顯式聲明為數組, -match在過濾模式下工作,表達式的結果不再是$true$false (簡化):

PS C:\> @(0) -match '^0$'
0

if()上下文使 PowerShell 將表達式結果轉換為[bool] ,並且由於0是一個值,因此if條件失敗。

更改 if 條件以檢查生成的過濾器模式表達式的計數

if(@($InstallerExitCodes -match "^(0|3010)$").Count -ge 1){
  # success!
}

或使用包含運算符來測試:

if($InstallerExitCodes -contains 0 -or $InstallerExitCodes -contains 3010){
  # success!
}

或者,你知道,單獨測試退出代碼,而不是作為一個集合:-)

暫無
暫無

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

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