You might use the $ExecutionContext.InvokeCommand.ExpandString method to evaluate the string expression:

Copy$test = 5
$myCheckTest = '$test -eq 4'
$ExecutionContext.InvokeCommand.ExpandString("`myCheckTest)")
False
$myCheckTest = '$test -eq 5'
$ExecutionContext.InvokeCommand.ExpandString("`myCheckTest)")
True

Note that the backtick (`) prevents the first dollar to be substituted so that you actual string expression will be something like: test -eq 4)
Or in your function:

Copyif ($ExecutionContext.InvokeCommand.ExpandString("`myCheckTest)")) {
    write-host "TEST MATCH"
} else {
    write-host "TEST NO MATCH"
}

A more common way to do thing like this is, is to use a scriptblock:

Copy$myCheckTest = {$test -eq 4}
$test = 5

if (&$myCheckTest) {
    write-host "TEST MATCH"
} else {
    write-host "TEST NO MATCH"
}
Answer from iRon 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
Please check out his blog at PowerShellExplained.com. Your scripts often need to make decisions and perform different logic based on those decisions. This is what I mean by conditional execution. You have one statement or value to evaluate, then execute a different section of code based on that evaluation. This is exactly what the if statement does.
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
How to combine multiple conditions in a PowerShell if-statement - Stack Overflow
How do you chain multiple sets conditions together when you want either one set or the other set of 2 conditions to be true? To be more precise, I want to do: If User is logged in AND Operating sys... More on stackoverflow.com
🌐 stackoverflow.com
If Statement Help
I created a script to copy groups from templates user names we have in a flat file on a network share. The script works good, however I’m having an issue with the If statements that give a status. I can’t get an if statement to work if no user was keyed into the textbox. More on forums.powershell.org
🌐 forums.powershell.org
4
0
August 21, 2013
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
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
🌐
PDQ
pdq.com › blog › how-to-use-if-statements-in-powershell
How to use if statements in PowerShell | PDQ
A PowerShell if statement evaluates a condition and runs a code block when that condition is true. PowerShell checks the expression in parentheses, and if it returns true, it executes the statements inside the braces.
🌐
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
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_if
about_If - PowerShell | Microsoft Learn
January 16, 2025 - When you run an if statement, PowerShell evaluates the <test1> conditional expression as true or false. If <test1> is true, <statement list 1> runs, and PowerShell exits the if statement.
🌐
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
🌐
Codecademy
codecademy.com › docs › powershell › conditionals
PowerShell | Conditionals | Codecademy
September 17, 2025 - Control program flow in PowerShell using if, else, elseif, and switch to execute code based on conditions.
🌐
AttuneOps
attuneops.io › powershell-if-else-and-elseif
Introduction to PowerShell If, Else, and ElseIf Statements - AttuneOps
September 30, 2025 - In PowerShell, decision-making helps your script decide what to do based on certain conditions. The if, else, and elseif statements are key for this. Think of them as checkpoints where you check a condition (true or false) and then tell the script what to do next.
🌐
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 - If the value was $false, then it would skip over that scriptblock. In the previous example, the if statement was just evaluating the $condition variable. It was $true and would have executed the Write-Output command inside the scriptblock. In some languages, you can place a single line of code after the if statement and it will get executed. That is not the case in PowerShell.
🌐
SS64
ss64.com › ps › if.html
If ( ) … elseif ( ) … else { } - PowerShell
If ($fruit -eq "orange") {'We found an orange'} ElseIf ($fruit -eq "apple") {'We found an apple'} ElseIf ($fruit -eq "pear") {'We found an pear'}
🌐
TutorialsPoint
tutorialspoint.com › powershell › if_else_statement_in_powershell.htm
Powershell - If Else Statement
if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }elseif(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }elseif(Boolean_expression 3) { // Executes when the Boolean expression 3 is true ...
🌐
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 - Let’s suppose we have a PowerShell script that prompts the user for input, and we want to check if the user entered a specific message, such as “Hello, world!”. We can use a here-string within an if statement PowerShell to compare the user input against the expected message. In the following example, the script prompts the user to enter a message, and we store the input in the $userInput variable. The if statement then compares the user’s input against the expected message using a here-string.
🌐
Thomas Maurer
thomasmaurer.ch › home › powershell: if statement basics
Powershell: if Statement basics - Thomas Maurer
December 22, 2020 - The if-statement is pretty important if you are creating PowerShell scripts. So I created this post to get some basic information about how to use if-else statements with PowerShell. PowerShell if-else statement basics Like many other languages, PowerShell has statements for conditionally executing ...
🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell if else statements
How to use PowerShell If Else Statements — LazyAdmin
May 9, 2023 - An if statement is often accompanied by an else statement in PowerShell. The else part of the statement is executed when the condition is false or null. Taking our last example, we can add an else statement that will tell us if the $num is less ...
🌐
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 - The If statement evaluates a condition and executes code if the condition is true. The Else statement executes code if the condition (or the Boolean expression) is false. The most commonly used conditional statement in PowerShell is the “if” ...
🌐
Computer Performance
computerperformance.co.uk › home › powershell
PowerShell Basics: If Statement. Also 'Else and 'ElseIf' constructions
January 9, 2019 - The logic says If the StatusCode is 0, then display a label saying ‘ON NETWORK’. # PowerShell If Statement To Test Ip Addresses $i =1 $Ip = "192.168.1." Write-Host "IP Address" Write-Host "----------------------------------------" Do { $Ip4th = $Ip + $i $Pingy = Get-WmiObject Win32_PingStatus -f "Address='$Ip4th'" If($Pingy.StatusCode -eq 0) { "{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode," ON NETWORK"} else {"{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode, " xxxxxxxxx" } $i++ } until ($i -eq 20)
🌐
PowerShell Forums
forums.powershell.org › powershell help
If Statement Help - PowerShell Help - PowerShell Forums
August 21, 2013 - I created a script to copy groups from templates user names we have in a flat file on a network share. The script works good, however I’m having an issue with the If statements that give a status. I can’t get an if statement to work if no user was keyed into the textbox.
🌐
ITPro Today
itprotoday.com › home › powershell
How To Use If Else Statements in PowerShell
June 4, 2024 - Let’s look at an If Else example. We’ll create an If Else statement that checks to see if $A is equal to 5. If $A does equal 5, then PowerShell will display the word “Match.” If $A is equal to something else, then PowerShell will display the words “No Match.”
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)
  }
}