How do I use an if statement for multiple conditions in PowerShell?

0
2
Asked By FunkyPineapple87 On

I'm working with a CSV file and trying to filter rows using an if statement. My goal is to select rows where column A has `file_1.txt` and column B has either `high` or `critical`. I'm currently using this code:

```powershell
if(($row.column_a -eq 'file_1.txt') -and ($row.column_b -eq 'high' -or $row.column_b -eq 'critical')) {
$row.column_c
}
```

However, it's not returning the expected 7 results from column C; I'm only seeing 5. I feel like there might be a better way to write this if statement but I'm not sure where I'm going wrong. Any suggestions? Thanks!

2 Answers

Answered By TechieTango21 On

Your condition looks a bit convoluted. Instead, you can simplify it by using the `-in` operator like this:

```powershell
if ($row.column_a -eq 'file_1.txt' -and $row.column_b -in @('high', 'critical')) {
$row.column_c
}
```

Also, check your quotes; you seem to have a ``` in your filename. That might be causing some issues.

FunkyPineapple87 -

Good catch on the backtick! I updated it in my code. I didn’t realize you could check against an array like that. Thanks!

Answered By JavaJolt99 On

First off, double-check your data for any leading or trailing spaces in your columns. You might want to trim those or use regex matching instead of strict equality. Try this:

```powershell
if ($row.column_a -match 'file_1.txt' -and $row.column_b -match 'high|critical') {
@row.column_c
}
```

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.