Put each set of conditions in parentheses:

if ( (A -and B) -or (C -and D) ) {
    echo do X
}

If either the first or the second set of conditions must be true (but not both of them) use -xor instead of -or:

if ( (A -and B) -xor (C -and D) ) {
    echo do X
}

Replace A, B, C, and D with the respective expressions.

Answer from Ansgar Wiechers on Stack Overflow
🌐
Reddit
reddit.com › r/powershell › if statement with multiple conditions
r/PowerShell on Reddit: If statement with multiple conditions
May 19, 2025 -

I have an if statement that I am using to select specific rows from a CSV. Column 1 has a filename in it and then column b has 1 of 4 strings in it comprised of low, medium, high, and critical. I want an if statement that selects the row if column a contains file_1.txt and column b contains either high or critical. I've tried the following:

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

It does not seem to be working correctly. I should be getting 7 results from column C, but I am only getting 5.

I think there's a better way to express this. Not sure where I am tripping up. Any help would be appreciated! Thanks in advance!

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1044404 › powershell-if-statement-to-include-more-conditions
powershell if statement to include more conditions - Microsoft Q&A
$jobtitle = 'teaching fellow' # this might be easier to maintain: $found = $false Switch -regex ($jobtitle) { '\bteacher\b' {$found = $true; break} '\bvisiting\b' {$found = $true; break} '\blecturer\b' {$found = $true; break} '\bteaching fellow\b' {$found = $true; break} '\beditor\b' {$found = $true; break} default {$found = $false} } if ($found){ "found it" } else{ "not there" } # # this is more compact, but harder to read and my become unwieldy if the number of choices increases if ($jobtitle -match '\bteacher|visiting|lecturer|teaching\sfellow|editor\b'){ "found it" } else{ "not there" }
Discussions

Powershell If statement with multiple conditions - Stack Overflow
I have a Powershell script with If statement and multiple conditions. My code is working great but I am looking for to display which condition my object doesn't respect. Get-ChildItem $Path -Direct... More on stackoverflow.com
🌐 stackoverflow.com
Powershell - Multiple if statements
I am writing a script that first of all checks to make sure a file is available. If it is not, my output is “Messenger is currently idle.” But if the file is available, I am pulling data from the file, starting with the datetime and comparing it to the currenttime. More on community.spiceworks.com
🌐 community.spiceworks.com
10
3
July 15, 2019
multiple if statement conditions
The problem is in you -eq A or B or C... the -eq only applies to A, logically what you have is if letter -eq A or B or C ... you need the comparison on each letter, e.g. letter -eq A or letter -eq B or letter -eq C .... You also could do away with the elseif and just use an if statement for each group. More on reddit.com
🌐 r/PowerShell
24
1
May 20, 2022
Multiple Variable Conditions for If Statement in PowerShell - Stack Overflow
Thanks for the help in this, I think i have over complicated the below but the logic just isn't responding how my mind is telling it too. Logic in Question: $a = "One" $b = "Two" $c = "Three" $d = " More on stackoverflow.com
🌐 stackoverflow.com
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to use the if else statement in powershell?
How to Use the If Else Statement in PowerShell? - SharePoint Diary
October 7, 2025 - Use the ElseIf statement when you have multiple conditions but only want to execute one block of code. Enter the elseif clause, sometimes spelled as else if in PowerShell or PowerShell elseif.
Top answer
1 of 2
3

If this is just for checking and not for keeping a log where you need those specific messages I might go for something simple where we just capture the true and false values for each of the tests.

$path = C:\temp
Get-ChildItem $Path -Directory -Force |
    ForEach-Object {
        [PSCustomObject]@{
            Folder         = $_.BaseName
            LastWriteTime  = $_.LastWriteTime
            FolderNameTest = $_.BaseName -match 'test'
            DateOKTest     = $_.LastWriteTime -lt (Get-Date).AddDays(-30)
        }
    }

Sample Output

Folder         LastWriteTime       FolderNameTest DateOKTest
------         -------------       -------------- ----------
.git           06.09.2021 01:06:06          False       True
.vscode        25.09.2021 10:06:11          False       True
1              22.09.2021 22:30:26          False       True
batch_test     02.05.2022 22:29:25           True      False
cleanup        20.09.2021 10:02:51          False       True
DeviceDatabase 26.09.2021 12:07:26          False       True
host           22.09.2021 23:23:38          False       True
move_logs      26.04.2022 19:28:59          False      False
test_run       01.03.2022 22:14:14           True       True

You can then pipe this to Export-Csv if you like

2 of 2
2

There are various ways to go about this; but this one is clean and easy to understand, so would be my preferred route:


Function Move-FolderConditional { # todo: give this cmdlet a better name for your context
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [System.IO.DirectoryInfo[]]$Path
        ,
        [Parameter(Mandatory)]
        [System.IO.DirectoryInfo]$Destination
        ,
        # files matching this pattern get moved to the target
        [Parameter(Mandatory)]
        [string]$ArchivableFolderPattern
        ,
        # Files older than this date get moved to the target
        [Parameter()]
        [string]$MinKeepDateUtc = (Get-Date).AddDays(-3).ToUniversalTime()
    )
    Process {
        foreach ($directory in $Path) {
            if ($directory.BaseName -notmatch $ArchivableFolderPattern) {
                Write-Warning "Could not move folder 'directory.FullName)' as the name does not match the required pattern"
                continue;
            }
            if ($directory.LastWriteTimeUtc -ge $MinKeepDateUtc) {
                Write-Warning "Could not archive folder 'directory.FullName)' as it was last updated at 'directory.LastWriteTimeUtc.ToString('u'))'"
                continue;
            }
            try {
                #Move-Item -Path $directory -Destination $Destination -ErrorAction Stop # Uncommend this if you actually want to move your files
                Write-Information "Successfully moved 'directory.FullName)' to 'Destination.FullName)'" 
            } catch [System.Management.Automation.ItemNotFoundException] { # For this exception we'd probably check in the Begin block instead - but this is just to give the idea that we could add a try/catch if required
                Write-Warning "Could not archive folder 'directory.FullName)' the target directory does not exist: 'Destination.FullName)'"
            }  
        }
    }
}

# Example usage
Get-ChildItem $path -Directory -Force | Move-FolderConditional -ArchivableFolderPattern '^log' -InformationAction Continue -Destination 'z:\archive\'

But other options are available (I've just included snippets to give the gist of these):

Switch Statement

switch ( $directory )
{
    {$_.BaseName -notmatch $ArchivableFolderPattern}
    {
        Write-Warning "Could not move folder '_.FullName)' as the name does not match the required pattern"
        break
    }
    {$_.LastWriteTimeUtc -ge $MinKeepDateUtc}
    {
        Write-Warning "Could not archive folder '_.FullName)' as it was last updated at '_.LastWriteTimeUtc.ToString('u'))'"
        break
    }
    default 
    {
        Write-Information "Successfully moved '_.FullName)' to 'Destination.FullName)'" 
    }
}

Flags

[bool]$archiveFolder = $true
if ($directory.BaseName -notmatch $ArchivableFolderPattern) {
    Write-Warning "Could not move folder 'directory.FullName)' as the name does not match the required pattern"
    $archiveFolder = $false
}
if ($directory.LastWriteTimeUtc -ge $MinKeepDateUtc) { 
    # note: this will process even if archivefolder is already false... you can use `else` or amend the condition to include `$archiveFolder -or ($directory.LastWriteTimeUtc -ge $MinKeepDateUtc)`; though if going that route it's better to use the switch statement.
    Write-Warning "Could not archive folder 'directory.FullName)' as it was last updated at '_.LastWriteTimeUtc.ToString('u'))'"
    $archiveFolder = $false
}
if ($archiveFolder) {
    Write-Information "Successfully moved 'directory.FullName)' to 'Destination.FullName)'" 
}

Other

Or you can do combinations of the above (e.g. use the switch statement to set your flags (in which case you can optionally remove the break so that all issues are displayed).

🌐
Computer Performance
computerperformance.co.uk › home › powershell
PowerShell Basics: If -And & If -Or Statements | Examples
January 9, 2019 - PowerShell If -And &If -Or statements. For scripts that require precise flow control you could incoroporate -And & -Or to test for multiple conditions.
🌐
PDQ
pdq.com › blog › how-to-use-if-statements-in-powershell
How to use if statements in PowerShell | PDQ
Think of elseif as the more elegant alternative to over-nesting. (Did that chicken-nest pun land?) PowerShell lets you combine multiple conditions inside a single if statement using logical operators like -and and -or.
🌐
Adam the Automator
adamtheautomator.com › powershell-if-statement
Back to Basics: Conditional Logic with PowerShell If Statement
The if statement contains the first ... The elseif statement is where you add conditions. You can add multiple ElseIf statements when you have multiple conditions....
Published   May 25, 2023
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › scripting › learn › deep-dives › everything-about-if
Everything you wanted to know about the if statement - PowerShell | Microsoft Learn
We can use normal PowerShell inside the condition statement. ... Test-Path returns $true or $false when it executes. This also applies to commands that return other values. ... It evaluates to $true if there's a returned process and $false if ...
🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › else if in powershell
Else If in PowerShell | Multiple or Single Conditional Operators in Else If
February 28, 2023 - As shown in the above diagram, If the statement contains a condition. If condition satisfies then it executes the block. If there are multiple if statements then script checks each if statement condition and executes whichever is true.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
AttuneOps
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
September 30, 2025 - Think of them as checkpoints where you check a condition (true or false) and then tell the script what to do next. For example, you can use if to check if a file exists, else to do something if it doesn’t, and elseif to handle multiple conditions.
🌐
Delft Stack
delftstack.com › home › howto › powershell › powershell if multiple conditions
How to Combine Multiple Conditions in if Statement | Delft Stack
February 2, 2024 - If this condition is met, it proceeds to the nested if statement, which checks if $number is less than or equal to 20. Only when both conditions are true does it execute the Write-Host command. In the output, both conditions are met, and printed out the message "The number is between 10 and 20.". In conclusion, combining multiple conditions in PowerShell’s if statement is essential for making efficient scripts.
🌐
Spiceworks
community.spiceworks.com › programming & development
Powershell - Multiple if statements - Programming & Development - Spiceworks Community
July 15, 2019 - I am writing a script that first of all checks to make sure a file is available. If it is not, my output is “Messenger is currently idle.” But if the file is available, I am pulling data from the file, starting with the …
🌐
Collecting Wisdom
collectingwisdom.com › home › powershell: how to use if statement with multiple conditions
PowerShell: How to Use If Statement with Multiple Conditions - Collecting Wisdom
February 27, 2024 - This if statement returns “Both ... does have a value greater than 8 · We can use the -or operator in PowerShell within an if statement to check if at least one condition is met....
🌐
PowerShell Test-Path
powershellfaqs.com › multiple-conditions-in-powershell-if-else-statement
How to Use Multiple Conditions in PowerShell If Else Statement?
July 8, 2024 - The -and operator in PowerShell allows you to combine two or more conditions, and the combined condition is true only if all individual conditions are true. Using the PowerShell —and operator, we can add multiple conditions in an if-else statement.
🌐
Java2Blog
java2blog.com › home › powershell › combine multiple conditions in if statement in powershell
Combine Multiple Conditions in if Statement in PowerShell - Java2Blog
May 2, 2023 - Use the if statement with two logical operators (-not and -or) and one comparison operator (-lt) to combine multiple conditions in PowerShell.
🌐
Reddit
reddit.com › r/powershell › multiple if statement conditions
r/PowerShell on Reddit: multiple if statement conditions
May 20, 2022 -

Hi,

I'm a noob here. I still suck at PowerShell. But I think this should be easy. I cant find an example of what I'm trying to do. It's either just one condition or something so complicated, I can't understand it.

# Define database variables/values

$A_through_F = "A_through_F"
$G_through_K = "G_through_K"
$L_through_P = "L_through_P"
$Q_through_U = "Q_through_U"
$V_through_Z = "V_through_Z"

Write-Host "Enter the user name in the format of first name space last name"
Write-Host "Enclose the users name in quotation marks"
$User = Read-Host "Please enter the user"

Write-host "Fetching $User properties..." -ForegroundColor red -BackgroundColor Black
Write-Host ""

$UserSurname = Get-ADUser -Filter * -Properties * -SearchBase "OU=??? Users,OU=???.com" -Server "MY_AD.MY_DOMAIN" | where-object Name -eq "$User" | select-object -ExpandProperty SN
#Gets Surname

$FirstCharacterSurName = $UserSurname.SubString(0,1)

Write-Host "The first character of the surname of the user you have entered is: $FirstCharacterSurName"

if ( $FirstCharacterSurName -eq "A" -or "B" -or "C" -or "D" -or "E" -or "F" )
{
    Write-Host "User belongs in $A_through_F database"
}

elseif ( $FirstCharacterSurName -eq "G" -or "H" -or "I" -or "J" -or "K" )
{
    Write-Host "User belongs in $G_through_K database"
}

elseif ( $FirstCharacterSurName -eq "L" -or "M" -or "N" -or "O" -or "P" )
{
    Write-Host "User belongs in $L_through_P database"
}

elseif ( $FirstCharacterSurName -eq "Q" -or "R" -or "S" -or "T" -or "U" )
{
    Write-Host "User belongs in $Q_through_U database"
}

else 
{
    Write-Host "User belongs in $V_through_Z database"
}

It pulls the first Character of the last name correctly. However, it always choose A_through_F for everything. Can you not have multiple conditions like this?

🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell if else statements
How to use PowerShell If Else Statements — LazyAdmin
May 9, 2023 - If And statements in PowerShell allow you to test for multiple conditions inside a single if. This sometimes eliminates the need for nested If statements or multiple if-else statements. If and statements check if two or more conditions are true.
Top answer
1 of 3
5

You can use Compare-Object to compare the value pairs as arrays:

if (Compare-Object $a, $b   $c, $d  -SyncWindow 0) {
  'different'
} else {
  'same'
}

Note that this is convenient, but relatively slow, which may matter in a loop with many iterations.

  • The Compare-Object cmdlet compares two arrays and by default returns information about their differences.

  • -SyncWindow 0 compares only directly corresponding array elements; in other words: $a must equal $c, and $b must equal $d; without -SyncWindow, the array elements would be compared in any order so that 1, 2 would be considered equal to 2, 1 for instance.

  • Using the Compare-Object call's result as a conditional implicitly coerces the result to a Boolean, and any nonempty result - indicating the presence of at least 1 difference - will evaluate to $True.


As for what you tried:

Use of { ... } in your conditional is not appropriate.
Expressions enclosed in { ... } are script blocks - pieces of code you can execute later, such as with & or .

Even if you used (...) instead to clarify operator precedence (-ne has higher precedence than
-and), your conditional wouldn't work as expected, however:

  • ($a -and $b) -ne ($c -and $d) treats all variables as Booleans; in effect, given PowerShell's implicit to-Boolean conversion, you're comparing whether one value pair has at least one empty string to whether the other doesn't.
2 of 3
3

In addition to the answer from mklement0 and avoiding the rather slow Compare-Object cmdlet:

In what you tried, you will need to compare one specific value with each of the rest of the vales:

($a -eq $b) -and ($a -eq $c) -and ($a -eq $d)

Because the Comparison Operators (-eq) take a higher precedence than the Logical Operators (-and), you can leave the brackets and simplify it to:

$a -eq $b -and $a -eq $c -and $a -eq $d

To make this code DRY and easily expandable for even more values:

if ($a, $b, $c | Where {$_ -ne $d}) {
  'different'
} else {
  'same'
}