我正在尝试从IF语句设置输出变量,但仅在满足条件的情况下设置,但如果不满足条件,则不更改该变量。由于某种原因,即使不满足条件,IF语句也会更改变量。如果条件失败,我该如何告诉IF语句不执行任何操作?
我最初是在IF语句的脚本块中将其设置为$ Output =“ Error”,但这只是将其设置为即使失败也不应该失败。
$Output = "Pass"
$ErrorCodes = 2, 26, 50, 48, 2820, 4239
$ErroredBackups = Import-Csv C:\temp\NetBackupJobs_GS.csv
foreach ($ErroredBackup in $ErroredBackups) {
$Output = if ($ErroredBackup.status -in $ErrorCodes) {
"Error"
}
}
$Output
CSV样本:
jobid,已启动,状态 334382,17 / 07/2019 16:35,0
当$ Output应该为“ Error”或“ Pass”时,我一直将$ Output留为空白
答案 0 :(得分:1)
在$Output = ...
块中移动分配(if
):
if ($ErroredBackup.status -in $ErrorCodes) {
$Output = "Error"
}
另一种可能是PowerShell惯用的方法可能是利用Where-Object
查找“确实失败”的备份:
$ErrorCodes = 2, 26, 50, 48, 2820, 4239
$ErroredBackups = Import-Csv C:\temp\NetBackupJobs_GS.csv
if($ErroredBackups |Where-Object status -in $ErrorCodes){
# At least one backup job must have had a terrible error code
"Error"
}
else{
# None found, pass
"Pass"
}