V Britt
V Britt

Reputation: 25

Filtering with the "AND" operator not working as expected in powershell

I am trying to filter data from a CSV file. There are 3 Columns OS1, OS2, and OS3. If any these 3 cells are anything but yes I need that row exported to another CSV file. Here is what I came up with:

$OSCOL = Import-csv $pwd\$Source\Win.csv | `
where {$_."OS1" -inotmatch "Yes" `
-and $_."OS2" -inotmatch "Yes" `
-and $_."OS3" -inotmatch "Yes" } `
| Export-Csv $pwd\ossla.csv -notypeinfo

However this is not working as expected... If 'any' of the cells are not 'Yes' then that row is not exported. So for example if my csv File is:

    servername,OS1,OS2,OS3
    serv1,yes,no,no
    serv2,yes,Yes,yes
    serv3,pending,yes,yes
    serv4,no,pending,no

I would want the output of:

    servername,OS1,OS2,OS3
    serv1,yes,no,no
    serv3,pending,yes,yes
    serv4,no,pending,no

However I what I am getting is:

    servername,OS1,OS2,OS3
    Serv4,no,pending,no

What am I doing wrong here?

Upvotes: 1

Views: 104

Answers (2)

user6811411
user6811411

Reputation:

Your logical -and is the error, if any one different than Yes should trigger output you'll need to use -or.
In your sample only the line where all 3 cols are not Yes are output.
Btw: you don't need to escape the line end following a pipe symbol. I changed this script which now needs no backticks.

$OSCOL = Import-csv .\Win.csv |
   where {$_."OS1" -inotmatch "Yes" -or
   $_."OS2" -inotmatch "Yes"  -or
   $_."OS3" -inotmatch "Yes" } |
     Export-Csv .\ossla.csv -notypeinfo

Output

> cat .\ossla.csv
"servername","OS1","OS2","OS3"
"serv1","yes","no","no"
"serv3","pending","yes","yes"
"serv4","no","pending","no"

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

You've got that logic backwards there.

What you want to test for is whether all cells match Yes and then grab those objects if that's not the case:

Import-Csv $PWD\$Source\Win.csv |where {-not(
$_."OS1" -match "Yes" -and 
$_."OS2" -match "Yes" -and 
$_."OS3" -match "Yes")}

Upvotes: 1

Related Questions