🌐
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
There are quite a few nuances when dealing with $null values in PowerShell. If you're interested in diving deeper, I have an article about everything you wanted to know about $null. I almost forgot to add this one until Prasoon Karunan V reminded me of it. if ($process=Get-Process notepad -ErrorAction Ignore) {$process} else {$false}
🌐
SS64
ss64.com › ps › if.html
If ( ) … elseif ( ) … else { } - PowerShell
Syntax if ( condition ) { commands_to_execute } [ elseif ( condition2 ) { commands_to_execute } ] [ else {commands_to_execute} ] Key Condition An expression that will evaluate to true or false, often utilising one or more comparison operators. commands_to_execute A PowerShell or external command ...
Discussions

Better Way to Create If/Elseif/Else Statement
You are doing the same thing in all cases, so really you could simplify the whole thing to if($userdepartment -in 'IT', 'Engineering', 'Finance', 'Human Resources', 'Sales') { Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath "OU=$userdepartment,OU=testlab.local Users,DC=testlab,DC=Local" } else { Write-Warning "Department $userdepartment could not be found." } More on reddit.com
🌐 r/PowerShell
29
43
August 14, 2021
windows - Powershell script if else statements - Stack Overflow
-U returns the else echo statement and I can't figure out why. Everything else works if just seems to be ignoring my first if statement. The script functions for folder navigation. -U should return... More on stackoverflow.com
🌐 stackoverflow.com
Help with "if" "else" statement
Appreciate your assistance with a script I am working on. The script extracts all computers from an OU and a file with two columns: Computer Name and ExtensionAttribute. I would also like to filter the list with an “if” “else” statement. If the value is X, move the computers to OU1. More on forums.powershell.org
🌐 forums.powershell.org
9
0
May 11, 2022
Alternative to IF statement
You could use a function with a switch or case select. function DoTheNeedful ([string]$Username) { # If the specified user is a match, return true, else return false switch ($Username) { "Username1" {return $true} "Username2" {return $true} "Username3" {return $true} Default {return $false} } } Then in your code you can do something like this: if(DoTheNeedful($Username)){ # Bypass user }else{ # Do not bypass user } That way you can update the function when you wish to add/remove a user. Another way to do it is like this: $UserBypassList = @( "Username1", "Username2" ) if($UserBypassList -contains $Username){ # Bypass user }else{ # Do not bypass user } You can also create a text file with a list of usernames and import it. $UserBypassList = get-content -Path .\UserBypassList.txt More on reddit.com
🌐 r/PowerShell
19
11
September 19, 2017
People also ask

Does PowerShell support a ternary operator like other languages do?
Yes, with PowerShell 7 and later, you can use a ternary operator. The syntax is:

$result = $condition ? 'TrueValue': 'FalseValue'

This is an efficient way for simple conditional assigning.
🌐
attuneops.io
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
Can I have multiple elseif statements in one script?
Yes, you can. PowerShell supports multiple elseif statements in the same script. They are evaluated in a top-to-bottom manner, and the first condition set to $true will run; everything else will be skipped out of the elseif statement.
🌐
attuneops.io
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
What is short-circuiting in PowerShell conditions?
In this context, short-circuiting is related to how PowerShell evaluates conditions and is used by operators such as -and and -or. For example, '-and' would only evaluate the second condition if the first condition was $true, whereas '-or' would not evaluate the second condition if the first condition was $false. In both situations, the short-circuiting behaviour saves time and avoids unnecessary evaluations.
🌐
attuneops.io
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
🌐
Server Academy
serveracademy.com › blog › how-to-use-the-if-else-statement-in-powershell
How to use the If Else Statement in PowerShell - Blog - ServerAcademy.com
One of the most powerful tools in PowerShell scripting is the ability to make decisions. The , , and statements allow you to control the flow of your script bas
🌐
PDQ
pdq.com › blog › how-to-use-if-statements-in-powershell
How to use if statements in PowerShell | PDQ
PowerShell checks each one in order, and as soon as it finds a condition that’s true, it runs that block and stops checking the rest. This makes elseif perfect for clean, readable logic when you're comparing a single value against multiple outcomes. Yes, I'm bringing back the eggs. $eggs = 14 if ($eggs -eq 12) { "You have exactly a dozen eggs."
🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell if else statements
How to use PowerShell If Else Statements — LazyAdmin
May 9, 2023 - Tip Want to learn more about writing ... often accompanied by an else statement in PowerShell. The else part of the statement is executed when the condition is false or null....
🌐
TutorialsPoint
tutorialspoint.com › powershell › if_else_statement_in_powershell.htm
Powershell - If Else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Following is the syntax of an if...else statement − If the boolean expression evaluates to true, then the if block of code will be
🌐
Reddit
reddit.com › r/powershell › better way to create if/elseif/else statement
r/PowerShell on Reddit: Better Way to Create If/Elseif/Else Statement
August 14, 2021 -

Hey Everyone!

I am fairly new to PowerShell and wanted to get some guidance on a potentially better way to utilize an If/Elseif/Else statement I have been using in an Active Directory script I made.

The following code snippet works great, but I have a feeling there is a much cleaner or efficient way of doing this. As you can see the more OU's present in the AD environment the more this elseif list grows. In the script that I used in a production environment, this list grew quite large as there was approximately 15 OUs present.

Is there a more efficient way to do this?

if ( $userdepartment -eq "IT" )
{
    Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath 'OU=IT,OU=testlab.local Users,DC=testlab,DC=Local'
}
elseif ( $userdepartment -eq "Engineering" )
{
    Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath 'OU=Engineering,OU=testlab.local Users,DC=testlab,DC=Local'
}
elseif ( $userdepartment -eq "Finance" )
{
    Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath 'OU=Finance,OU=testlab.local Users,DC=testlab,DC=Local'
}
elseif ( $userdepartment -eq "Human Resources" )
{
    Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath 'OU=Human Resources,OU=testlab.local Users,DC=testlab,DC=Local'
}
elseif ( $userdepartment -eq "Sales" )
{
    Get-ADUser "$($uservaluefirstletter)$($uservaluelast)".ToLower() | Move-ADObject -TargetPath 'OU=Sales,OU=testlab.local Users,DC=testlab,DC=Local'
}
else
{
    Write-Warning "Department $userdepartment could not be found."
}

Thank you to anyone who takes the time to read this and gives guidance on this!

Find elsewhere
🌐
AttuneOps
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
September 30, 2025 - These statements make your scripts ... how they can make your scripts smarter and more efficient. ... An if statement evaluates whether a condition is true or false....
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_if
about_If - PowerShell | Microsoft Learn
January 16, 2025 - You can use the if statement to run code blocks if a specified conditional test evaluates to true. You can also specify one or more additional conditional tests to run if all the prior tests evaluate to false.
🌐
PowerShell Test-Path
powershellfaqs.com › if-else-statements-in-powershell
How to Use if-else Statements in PowerShell?
July 8, 2024 - Sometimes, you may need to check multiple conditions inside a PowerShell script. PowerShell allows you to use elseif to handle such scenarios: $number = 7 if ($number -gt 10) { Write-Output "The number is greater than 10." } elseif ($number -eq 10) { Write-Output "The number is exactly 10."
Top answer
1 of 2
2

If you want parameters to do something mutually exclusive and show help only if none are specified, you need to chain all your checks in a single if ... elseif ... elseif ... else chain:

Copy    if ($Username) {
        $targetFolder += '\user\swmur'
    }
    elseif ($Scripts) {
        $targetFolder += '\Desktop\Scripts'
    } 
    elseif ($Desktop) {
        $targetFolder += '\Desktop'
    }
    elseif ($root) {
        $targetFolder += 'c:\'
    }
    else {
        echo "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
    }

2 of 2
2

I added some colorful commentary. This should be pretty close to what you're looking for.

Copyfunction display-path {
  <#
    .SYNOPSIS
    quick shortcut to get env:PATH

    .DESCRIPTION
    Call Get-ChildItem with the the -path set to "env:Path" which actually just outputs out the child items of the current folder...

    .EXAMPLE
    display-path | Format-List


    Name  : Path
    Value : C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPow
          erShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\ProgramData\chocolatey\bin;C:\Program Files\Go\bin;C:\Program 
          Files\dotnet\;C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\Syste
          m32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\ProgramData\chocolatey\bin;C:\Program 
          Files\Go\bin;C:\Program Files\dotnet\;C:\Python310\Scripts;C:\Users\jedurham\AppData\Local\Programs\Microsoft VS Code\bin

    .NOTES
    not sure why anyone needs this

#>

  Get-ChildItem -Path Env:Path 
}



function folder {
  <#
    .SYNOPSIS
    shortcut to move between folder someone uses often

    .DESCRIPTION
    shortcut to move between folder someone uses often. 
    can be used to quickly navigate to common directories.

    .PARAMETER Username
    Moves to the C:\Users\currentuser\ Folder.

    .PARAMETER Scripts
    Moves to a hard coded path called 'C:\Users\currentuser\Desktop\Scripts'

    .PARAMETER Desktop
    Moves to a hard coded path called 'C:\Users\currentuser\Desktop\'

    .PARAMETER Help
    Displays this file.

    .PARAMETER root
    Moves to the root of the current drive. 


    .EXAMPLE
    folder -Username
    C:> folder -U
    You chose the -U  flag!! Moving to C:\Users\currentuser\

    .EXAMPLE
    folder -Scripts

    C:> folder -S
    You chose the -S  flag!! Moving to C:\Users\currentuser\Desktop\Scripts

    .EXAMPLE
    folder -Desktop

    C:> folder -D
    You chose the -D flag!! Moving to C:\Users\currentuser\Desktop\
    

    .EXAMPLE
    folder -root
    C:\> folder -r
    You chose the -R flag!! Moving to C:\

    .NOTES
    Needs a lot of work .... 

    v0.01

#>



  [CmdletBinding(DefaultParameterSetName = 'Default')]
  param(
    [Alias('u')]
    [Parameter(ParameterSetName = 'User')]
    [switch]$Username
    ,
    [Alias('s')]
    [Parameter(ParameterSetName = 'Scripts')]
    [switch]$Scripts
    ,
    [Parameter(ParameterSetName = 'Desktop')]
    [Alias('d')]
    [switch]$Desktop
    ,
    [Alias('h')]
    [Parameter(ParameterSetName = 'help')]
    [switch]$Help
    ,
    [Alias('r')]
    [Parameter(ParameterSetName = 'root')]
    [switch]$root
  )



  $switchoutput = 'You chose the{0} flag!! Moving to {1}{2}'


  if ($Username) {

    ## you need more comments in your code
    ## are you just trying to move the \user\current logged in?
    ## just use $env:USERPROFILE

    $targetFolder = $env:USERPROFILE
    $u = ' -U'
    Write-Output -InputObject ($switchoutput -f $U, $targetFolder, '')


  }
  elseif ($Scripts) {

    ## a little tougher here because you need to hard code this path
    ## we could also ask for it ask an addendum to this switch :P
    ## ill do it this way

    $targetFolder = $env:USERPROFILE
    $s = ' -S '
    ## it might be better to define this else 

    $scriptspath = 'Desktop\Scripts'
    $targetFolder = $env:USERPROFILE + $scriptspath

    Write-Output -InputObject ($switchoutput -f $S, $targetFolder, '')

  }


  elseif ($Desktop) {

    ## same as above
    ## it might be better to define this else

    $desktop = '\Desktop\'
    $targetFolder = $env:USERPROFILE + $desktop
    $d = ' -D '

    Write-Output -InputObject ($switchoutput -f $d, $targetFolder, '')


  }
  elseif ($root) {

    ## same as other but we can use $env:homedrive for the root of C:

    $targetFolder = $env:HOMEDRIVE + '\'
    $r = ' -R '

    Write-Output -InputObject ($switchoutput -f $r, $targetFolder, '')
  }


  else {
    Write-Output -InputObject "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
        -R         Change to the Root of home directory"

  }

  if (Test-Path -Path $targetFolder) {
    Set-Location -LiteralPath $targetFolder -Verbose
  }
  else {
    Write-Output -InputObject ('{0} was not found :( exiting' -f $targetFolder)
  }
}
🌐
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 - If condition1 returns false, it moves to evaluate condition2. If condition2 returns true, PowerShell executes the elseif blocks. If both conditions return false, PowerShell executes the command in the else block.
🌐
TheSleepyAdmins
thesleepyadmins.com › 2024 › 03 › 03 › powershell-beginners-guide-using-if-else-statements
PowerShell Beginner’s Guide – Using IF Else Statements
March 3, 2024 - In this post we will be going through using if else statements. If else statement in PowerShell evaluates a condition and executes code if the condition is true. If the condition is false, alternative code is executed.
🌐
Adam the Automator
adamtheautomator.com › powershell-if-statement
Back to Basics: Conditional Logic with PowerShell If Statement
If you check for just a specific value, such as if ($Value) { } then PowerShell will test if the $Value is not $Null, 0, $False, an empty string, or an empty array. Pasting the code above into PowerShell will give you the result shown below.
Published   May 25, 2023
🌐
ITPro Today
itprotoday.com › home › powershell
How To Use If Else Statements in PowerShell
June 4, 2024 - An If Else statement causes PowerShell to perform one action if the specified condition is satisfied and perform a different action if the condition is not satisfied. The first half of an If Else statement (i.e., the If statement) is identical ...
🌐
Powershellexplained
powershellexplained.com › 2019-08-11-Powershell-if-then-else-equals-operator
Powershell: Everything you wanted to know about the IF statement
August 11, 2019 - The pipeline is a very unique and important feature of PowerShell. Any value that is not suppressed or assigned to a variable gets placed in the pipeline. The if provides us a way to take advantage of the pipeline in a way that is not always obvious. $discount = if ( $age -ge 55 ) { Get-SeniorDiscount } elseif ( $age -le 13 ) { Get-ChildDiscount } else { 0.00 } Each script block is placing the results the commands or the value into the pipeline.
🌐
Petri
petri.com › home › how to use powershell if statements to add conditional logic to your scripts
How to Use PowerShell If Statements | Petri IT Knowledgebase
December 5, 2025 - The If statement PowerShell checks whether the value of $number is greater than 0 using the -gt operator. When the condition is true, it executes the block of code within the first set of curly braces, which in this case prints “The number is positive.” · When the condition is false, it moves to the Elseif block and checks if the number is less than 0 using the -lt operator.
🌐
PowerShell Forums
forums.powershell.org › powershell help
Help with "if" "else" statement - PowerShell Help - PowerShell Forums
May 11, 2022 - Appreciate your assistance with a script I am working on. The script extracts all computers from an OU and a file with two columns: Computer Name and ExtensionAttribute. I would also like to filter the list with an “if” “else” statement. If the value is X, move the computers to OU1.
🌐
Microsoft Certified Professional Magazine
mcpmag.com › articles › 2016 › 03 › 09 › working-with-the-if-statement.aspx
PowerShell Basics: Working with the If Statement -- Microsoft Certified Professional Magazine Online
March 9, 2016 - Working in PowerShell, there will be times that you need to perform some sort of comparison to determine what kind of action should take place. To do that one possibly option is to look at using an If statement and also an Else statement that usually will accompany it to handle the result that doesn't occur with the If.