I build an array of objects and I am interested in recording if there is an error. Array of objects starts out like this
[array]$UsersResults = $GSuspend | ForEach-Object {
gam update user $_.primaryEmail archived on | Out-Null
[PSCustomObject]@{
Email = $_.primaryEmail
Error = $LASTEXITCODE
}
}
I simply want to know if any error is not 0.
If every error is 0. Later down my script I remove the error column from the array but I am pretty sure the following logic below is flawed.
If (-not ($UsersResults.error -notcontains 0)) {
Is there a simple way for me to find a error number above 0 or only add error to the array in the top part of the script if an error is found?
CodePudding user response:
Use Where-Object
to filter the array based on the value of the Error
column:
$failedResults = $UsersResults |Where-Object Error -ne 0
if($failedResults.Count -gt 0){
Write-Warning "'$($failedResults.Count)' errors occurred!"
}
else {
Write-Host "No errors occurred!"
}
If you want the result to just be a flat array of Email adresses, use $UsersResults.Email
or $UsersResults |ForEach-Object Name
. If you want a new array of objects with the Email
property preserved, but no Error
property, use $UsersResults |Select-Object Email