[英]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
,它返回由項目2
和3
組成的數組,因為他們滿足約束-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.