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"
    }

Answer from n0rd on Stack Overflow
🌐
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 ... 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 ...
🌐
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!

Discussions

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
Select String - If Else Statement - Powershell
Find answers to Select String - If Else Statement - Powershell from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
April 12, 2017
Scripting Powershell if/else statement on config match - Programming & Development - Spiceworks Community
Hey guys, Trying to formulate a script to check a VM for a config variable and then acting apon that depending on the result. I have the results pulling from a text file of machines. So far a snippet I have a problem with is below: foreach ($vm in $vms) { $binfo = Get-VM | Select ... More on community.spiceworks.com
🌐 community.spiceworks.com
1
June 20, 2017
Powershell: Conditional variable assignment in If ElseIf statement
So, I think we’re gonna see a few posts from me today as I continue to debug this script… If I just need to update one singular post as we go, let me know. But I’m sure each issue is going to be a little different and spread out. I’m building upon an AD User creation script I’ve written ... More on community.spiceworks.com
🌐 community.spiceworks.com
11
6
July 10, 2019
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
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
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
🌐
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
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_if
about_If - PowerShell | Microsoft Learn
January 16, 2025 - The ternary operator behaves like the simplified if-else statement. The <condition> expression is evaluated and the result is converted to a boolean to determine which branch should be evaluated next: The <if-true> expression is executed if the <condition> expression is true
🌐
SS64
ss64.com › ps › if.html
If ( ) … elseif ( ) … else { } - PowerShell
Syntax if ( condition ) { ... true or false, often utilising one or more comparison operators. commands_to_execute A PowerShell or external command to run if the condition is true....
Find elsewhere
🌐
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.
🌐
AttuneOps
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
September 30, 2025 - If the condition is false, the code inside the block is ignored and the script moves on. ... The else statement comes after an if block and runs when the condition in the if statement is false.
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)
  }
}
🌐
Easy IT Tutorials
easyittutorials.wordpress.com › 2020 › 01 › 23 › powershell-if-else-statement
PowerShell: If…Else Statement
January 23, 2020 - As we learned, the If statement ... action being executed. The Else statement, in combination with the If statement, allows for an action to take place when the condition in the If statement is not met....
🌐
Rene Nyffenegger
renenyffenegger.ch › notes › Windows › PowerShell › language › statement › if › index
PowerShell: if, if else, if elseif else
Simple if ($cond) { $expr_true ... with PowerShell 7. An if, elseif, …, else statement allows to check a series of conditions (cond_1, …, cond_n) and executes the body of the first condition that is true....
🌐
Dell
dell.com › support › contents › en-sm › article › product-support › self-support-knowledgebase › locate-service-tag › notebook
Locate Your Laptop's Service Tag | Dell US
Access your laptop's Service Tag (ST) or Express Service Code (EX) on the bottom cover or via BIOS/UEFI, Command Prompt, PowerShell, or SupportAssist.
🌐
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
🌐
Experts Exchange
experts-exchange.com › questions › 29015684 › Select-String-If-Else-Statement-Powershell.html
Solved: Select String - If Else Statement - Powershell | Experts Exchange
April 12, 2017 - Select allOpen in new window is there way to add if else statement to it? the result is "MB" or "KB" I want to covert it to GB, how do I do this?
🌐
Spiceworks
community.spiceworks.com › programming & development
Scripting Powershell if/else statement on config match - Programming & Development - Spiceworks Community
June 20, 2017 - Hey guys, Trying to formulate a script to check a VM for a config variable and then acting apon that depending on the result. I have the results pulling from a text file of machines. So far a snippet I have a problem with is below: foreach ($vm in $vms) { $binfo = Get-VM | Select {$_.ExtensionData.Config.Firmware} if ($binfo -contains ‘efi’){ Write-host “EFI Found” } else { Write-Host “Using Bios mode” } } The Issue I have is the if/else statement does not work correctly, I get the s...
🌐
Power Sysadmin Blog
poweradm.com › home › understanding if, else statements in powershell
Understanding IF, ELSE Statements in PowerShell - Power Sysadmin Blog
June 29, 2023 - The If statement is used to check a condition and perform a particular action if the condition is true. If the condition is not true (FALSE), you can use Else or ElseIf to perform another action.
🌐
W3Schools
w3schools.io › powershell-if-examples
Learn Powershell If else conditional statement tutorial and examples - w3schools
Powershell provides the following types conditional statements ... if else statements : executes commands inside if block when condition is True, else else block code executes.
🌐
Beatnik
dev.beatnik.co.il › news › powershell-if-else-statement
Powershell If Else Statement - Beatnik
3 weeks ago - Meanwhile, remote work and distributed ... critical time. At its core, the Powershell If Else Statement executes different blocks of code based on evaluated conditions....
🌐
Minerstat
wildcard.minerstat.com › news › powershell-if-else-if-else
Powershell If Else If Else - Minerstat
2 weeks ago - One such cornerstone in Windows scripting is If Else If Else: a simple yet essential control structure that guides logic and decision-making in automated tasks. Whether managing systems, monitoring environments, or building robust workflows, understanding when and how to use this construct can transform how developers and sysadmins approach coding challenges. With increasing demand for efficient, reliable automation, discussions around structured conditional logic in PowerShell have surged—reflecting real-world needs for precision, safety, and performance.
Top answer
1 of 11
2
> Omega Mastodon:

if ($ISResponse -eq “y” -or “Y”) {


You have to spell that out for powershell

a switch statement could do that for you though it’s not case sensitive, unless you tell it to.

# should be
if ($ISResponse -eq "y" -or $ISResponse -eq "Y") {

#with a switch statemtn

switch($ISResponse){
    y {<#do something#>}
    default{<#do something else#>}
}   

2 of 11
6

So, I think we’re gonna see a few posts from me today as I continue to debug this script… If I just need to update one singular post as we go, let me know. But I’m sure each issue is going to be a little different and spread out.

I’m building upon an AD User creation script I’ve written and am in need of a little more flexibility. The company sometimes creates multiple AD user objects for a singular person depending on if they are also needed at the “sister company” (literally the building next door…) Nothing is really separated in terms of AD forests, but I do sort them into a separate container and label them so that it’s easier to find/sort. So I want the script to prompt if this is a “OtherCompany” user, and change the variables automatically.

Now, onto the script… I’m attempting to set variables inside this If / ElseIf statement, and it doesn’t appear to be working. If I run this code inside ISE and then check ($DISPLAYNAME) in the console… it displays

Test User (OtherCompany)

This happens whether or not I say “Y” or “N”.

# Set additional required variables with input given for user
$DISPLAYNAME = "$FirstName $LastName"
$SAM = $FirstName + $LastName.SubString(0,1)
$DNSROOT = '@' + (Get-ADDomain).dnsroot
$UPN = $SAM + “$DNSROOT”

  Write-Host "Is this an OtherCompany user?" -ForegroundColor Yellow
     $ISResponse = Read-Host "[Y] Yes, [N] No"
        if ($ISResponse -eq "y" -or "Y") {
            $COMPANY = "OtherCompany"
            $DISPLAYNAME = "$DISPLAYNAME (OtherCompany)"
            $EmployeeEmail "$FirstName.$LastName@othercompany.com"
            $SAM = "$SAM-IS"
            $UPN = $SAM + "$DNSROOT"
                } elseif ($ISResponse -eq "n" -or "N"){
                            $COMPANY = "Contoso"
                            $EmployeeEmail = "$FirstName.$LastName@contoso.com" 
}

Now, I’m seeing some conflicting information online. A few different posts say that Powershell does not support conditional assignment (interesting for a scripting language…) but that answer doesn’t hold up when I use another script I wrote. This one converts IP addresses for a Barracuda web/email filter. The only difference I can ascertain is that I’m using -like rather than -eq in this script… but this works as expected

$CIDR = Import-Csv -Path $fullimport | Select-Object CIDR,IP | ForEach-Object{
    if( $_.CIDR -like 1 ) { $SubMask = "128.0.0.0"
        $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
     
        } elseif ( $_.CIDR -like 2 ) { $SubMask = '192.0.0.0' 
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
        
        } elseif ( $_.CIDR -like 3 ) { $SubMask = '224.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
  
        } elseif ( $_.CIDR -like 4 ) { $SubMask = '240.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
   
        } elseif ( $_.CIDR -like 5 ) { $SubMask = '248.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
  
        } elseif ( $_.CIDR -like 6 ) { $SubMask = '252.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'

        } elseif ( $_.CIDR -like 7 ) { $SubMask = '254.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
 
        } elseif ( $_.CIDR -like 8 ) { $SubMask = '255.0.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'
        
        } elseif ( $_.CIDR -like 9 ) { $SubMask = '255.128.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')' 
        
        } elseif ( $_.CIDR -like 10 ) { $SubMask = '255.192.0.0'
                $IP = $_.IP + ',' + $SubMask + ',' + 'Block' + ', ' + $Reason + ' ' + $Country + ' (' + $Owner + ')'

etc...etc...etc...more CIDRS.. Y'know
🌐
TutorialsPoint
tutorialspoint.com › powershell › if_statement_in_powershell.htm
Powershell - If Statement
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed.