问题
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.
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)
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.
This works for a single value:
$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"}}
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.
回答1:
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" }
Since 4
is not in $errors
, it returns Pass
$errors = 1,2,3,5,6
$ErroredBackup = 5
if ($ErroredBackup -in $errors) { "Error" } else { "Pass" }
Since 5
is in $errors
, it returns Error
回答2:
Use an -OR
statement in your condition.
$ErroredBackups = Import-Csv "C:\temp\NetBackupJobs_GS.csv"
foreach ($ErroredBackup in $ErroredBackups.status) {
If (@($ErroredBackup -eq "2" -OR $ErroredBackup -eq "26" -OR $ErroredBackup -eq "50" -OR $ErroredBackup -eq "48" -OR $ErroredBackup -eq "2820" -OR $ErroredBackup -eq "4239")) {
$Output="Error"
write-host $Output
} else{
$Output="Pass"
write-host $Output
}
}
--OR--
You can use -match
$errorArr = "2","26","50","48","282","4239"
$ErroredBackups = Import-Csv "C:\temp\NetBackupJobs_GS.csv"
foreach ($ErroredBackup in $ErroredBackups.status) {
if ($errorArr -match $ErroredBackup){$Output="Error"}else{$Output="Pass"}
write-host $Output
}
--OR--
Use compare-object
and then do a conditional check on the SideIndicator
$errorArr = "2","26","50","48","2820","4239"
$ErroredBackups = Import-Csv "C:\temp\NetBackupJobs_GS.csv"
foreach ($ErroredBackup in $ErroredBackups.status) {
$Output = compare-object $errorArr $ErroredBackup
IF ($Output.SideIndicator -eq '=>'){write-host 'Pass'}else{write-host 'Error'}
}
来源:https://stackoverflow.com/questions/57099336/compare-array-variable-with-list-of-possible-values