将数组变量与可能值列表进行比较 [英] Compare array variable with list of possible values
问题描述
我需要将数组中的值与可能结果的列表进行比较,然后根据列表是否匹配,在变量中返回值.
I need to compare a value from an array with a list of possible results, and then return a value in a variable depending on whether the list is matched or not.
即我有一个名为$ErroredBackup
的数组,其列为"status"
我需要将每个$ErroredBackup.Status
与可能的数字列表进行比较,如果匹配,请将$ output变量设置为Error.如果不匹配,请保持$output
变量不变(我将其设置为Pass开头)
i.e. I have an array called $ErroredBackup
with a column "status"
I need to compare each $ErroredBackup.Status
with a list of possible numbers, and if it matches set a $output variable to Error. If it doesn't match, leave the $output
variable as is (I set it to Pass to start with)
我尝试使用-contain
,但这似乎是另一回事-比较具有单个值的数组,而不是将单个值与列表进行比较.
I've tried using -contain
, but that seems to be the other way round - comparing an array with a single value, not comparing a single value with a list.
这适用于单个值:
$Output="Pass"
$ErroredBackups = Import-Csv C:\temp\NetBackupJobs_GS.csv
foreach ($ErroredBackup in $ErroredBackups) {If ($ErroredBackup.status -eq 26) {$Output="Error"}}
但是我需要一个值范围:
But I need a range of values:
$Output="Pass"
$ErroredBackups = Import-Csv C:\temp\NetBackupJobs_GS.csv
foreach ($ErroredBackup in $ErroredBackups) {If ($ErroredBackup.status -eq 2,26,50,48,2820,4239) {$Output="Error"}}
我想要的是让foreach
循环通过数组,如果它在.status列中找到任何列出的值,则会将$output
的值更改为错误",否则它将离开称为通过".最终的结果是将通过"或错误"写入文本文件,然后使用我们的网络监视工具解析该文件,并在发现错误时发出警报.
What I'd like is for the foreach
loop to go through the array and if it finds any of the listed values in the .status column it changes the value of $output
to "Error", else it leaves it as "Pass". The end result of this will be to write either Pass or Error to a text file and then use our network monitoring tool to parse that file and alert if it finds Error.
推荐答案
正如Lee_Dailey所说,in
-运算符是您所需要的.下面是一个简化的示例
As Lee_Dailey said, the in
-operator is what you need. Below is a simplified example
$errors = 1,2,3,5,6
$ErroredBackup = 4
if ($ErroredBackup -in $errors) { "Error" } else { "Pass" }
由于4
在$errors
中不是不是,因此它返回Pass
Since 4
is not in $errors
, it returns Pass
$errors = 1,2,3,5,6
$ErroredBackup = 5
if ($ErroredBackup -in $errors) { "Error" } else { "Pass" }
由于$errors
中的5
是,因此它返回Error
Since 5
is in $errors
, it returns Error
这篇关于将数组变量与可能值列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!