Looks like you're trying to create the directories if your user chooses one of 3 text phrases and the directory doesn't already exist, and complain to your user if they choose something other than the 3 text phrases. I would treat each of those cases separately:

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If ($text -in $AcceptableText)
{
    If (!(Test-Path $Path\$text)) 
    {
        new-item -ItemType directory -path $Path\$text
    }
}
Else
{
    write-host "invalid input"
}

Or you could test for the existence of the directory first like this:

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (!(Test-Path $Path\$text))
{
    If (($text -in $AcceptableText)) 
    {
        new-item -ItemType directory -path $Path\$text
    }
    Else
    {
        write-host "invalid input"
    }
}

Edit

Or, if you want to be tricky and avoid the Test-Path (as suggested by @tommymaynard), you can use the following code (and even eliminate the Try|Catch wrappers if you don't want error checking)

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (($text -in $AcceptableText)) 
{
    try { mkdir -path $Path\$text -ErrorAction Stop } #Change to -ErrorAction Ignore if you remove Try|Catch
    catch [System.IO.IOException] { } #Do nothing if directory exists
    catch { Write-Error $_ }        
}
Else
{
    write-host "invalid input"
}

Edit

Also worth noting that there are many ways to Use PowerShell to Create Folders.

Answer from Matthew on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_comparison_operators
about_Comparison_Operators - PowerShell | Microsoft Learn
The following example demonstrates ... and has two properties, File and Size. The Equals() method returns True if the File and Size properties of two MyFileInfoSet objects are the same....
Top answer
1 of 4
8

Looks like you're trying to create the directories if your user chooses one of 3 text phrases and the directory doesn't already exist, and complain to your user if they choose something other than the 3 text phrases. I would treat each of those cases separately:

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If ($text -in $AcceptableText)
{
    If (!(Test-Path $Path\$text)) 
    {
        new-item -ItemType directory -path $Path\$text
    }
}
Else
{
    write-host "invalid input"
}

Or you could test for the existence of the directory first like this:

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (!(Test-Path $Path\$text))
{
    If (($text -in $AcceptableText)) 
    {
        new-item -ItemType directory -path $Path\$text
    }
    Else
    {
        write-host "invalid input"
    }
}

Edit

Or, if you want to be tricky and avoid the Test-Path (as suggested by @tommymaynard), you can use the following code (and even eliminate the Try|Catch wrappers if you don't want error checking)

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (($text -in $AcceptableText)) 
{
    try { mkdir -path $Path\$text -ErrorAction Stop } #Change to -ErrorAction Ignore if you remove Try|Catch
    catch [System.IO.IOException] { } #Do nothing if directory exists
    catch { Write-Error $_ }        
}
Else
{
    write-host "invalid input"
}

Edit

Also worth noting that there are many ways to Use PowerShell to Create Folders.

2 of 4
5

Yes you can :) Note that in the switch statement, default is being executed when all the other cases are not matched. Please test it and let me know.

$text = [Microsoft.VisualBasic.Interaction]::InputBox(title,"")
if (!(Test-Path $Path\$text))
{
    switch ($text)
    {
        "Specific Text1"
        {
            new-item -ItemType directory -path $Path\$text
        }
        "Specific Text2"
        {
            new-item -ItemType directory -path $Path\$text
        }
        "Specific Text3"
        {
            new-item -ItemType directory -path $Path\$text
        }
        default
        {
            write-host "invalid input"
        }
    }
}
Discussions

Using an If Statement to check a String *
if ($arecord.ARecordName -contains "https://*.") This is a common misconception, but -contains is for searching the elements of arrays and it does not support wildcards. For string comparison use -match or -like. To escape the * in -like use the grave or backtick character. if ($arecord.ARecordName -like "https://`*.*") The second asterisk is used here without escaping as a wildcard. More on reddit.com
🌐 r/PowerShell
10
1
March 8, 2023
PowerShell $null Variable in an IF Statement
I know I’m going to be kicking myself, but since I still consider myself a n00b with PS, I’ll try not to kick too hard. I’ve got a script for new hires that works intermittently. HR insists that AD accounts use a person’s legal name, however many people prefer their nicknames for their ... More on community.spiceworks.com
🌐 community.spiceworks.com
8
5
March 10, 2016
PowerShell if-statement with a condition in a string - Stack Overflow
I have a condition stored in a string variable and I want to use this in an if-statement. In this example there is always a match, as the variable is not zero or null, etc. It's not "executing... More on stackoverflow.com
🌐 stackoverflow.com
If A or B equals C
Hi All, I was writing a function today where I need the outcome to be true if A or B equal C, where see is the results of a Get-ItemProperty Originally I had: If $a -eq Get-ItemProperty… Of course in order to avoid running the Get-ItemProperty cmdlet twice (due to needing to comapre it against ... More on forums.powershell.org
🌐 forums.powershell.org
0
0
August 20, 2019
🌐
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.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_if
about_If - PowerShell | Microsoft Learn
January 19, 2024 - 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.
🌐
Powershellexplained
powershellexplained.com › 2019-08-11-Powershell-if-then-else-equals-operator
Powershell: Everything you wanted to know about the IF statement
Like many other languages, PowerShell has statements for conditionally executing code in your scripts. One of those statements is the if statement. Today we will take a deep dive into one of the most fundamental commands in PowerShell. Index Index Conditional execution The if statement Comparison operators -eq for equality...
🌐
Codecademy
codecademy.com › docs › powershell › operators
PowerShell | Operators | Codecademy
June 8, 2023 - Equality operators in PowerShell are binary operators that compare two integer or string values that return True if the operator condition is met, otherwise False.
Find elsewhere
🌐
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
🌐
Reddit
reddit.com › r/powershell › using an if statement to check a string *
r/PowerShell on Reddit: Using an If Statement to check a String *
March 8, 2023 -

Hello Everyone. First, Apologies on this question. I know this has had to have been asked before but I'm not sure exactly how to word the question and all searches give me a ton of results for the wrong thing. (Wild card searches in this case)

The issue I'm having, I'm writing a script that is checking and creating some website information from a CSV. I'm creating these website URLs from ARecords and CName records pulled from DNS. Unfortunately, some of those records using * for wildcard in the DNS entries. So I get a list of websites with https://*.website.com

I'm attempting to use if statements to get rid of these instances. The problem I'm running into to is using the condition with a string * in it. For example:

if ($arecord.ARecordName -contains "https://*.") <- Is going to look for wildcard(anything) in between https:// and .

When attempting to use ` before *, it errors out. Single quotes around the outside are also not removing the * search.

At this point, I'm at a loss and just wanted to throw out something that is probably relatively easy into the world to see if someone can throw me a bone.

🌐
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
When you use a comparison operator, the value on the left-hand side is compared to the value on the right-hand side. The -eq does an equality check between two values to make sure they're equal to each other.
🌐
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 - With PowerShell, you can use the OR operator to evaluate these conditions. In this example, the script uses the OR operator to check if the $osVersion variable is equal to either “Windows Server 2016” or “Windows Server 2019”. If the ...
🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell if else statements
How to use PowerShell If Else Statements — LazyAdmin
May 9, 2023 - $value = 10 $value -gt 5 ? (Write-Host 'Greater than 5') : (Write-Host 'Less than or equal to 5') Another common practice is to check if a variable or result from a cmdlet is null or not. A null variable is a variable that has not been assigned a value or has been explicitly assigned a null value. Simply set, a null variable doesn’t have any data stored in it. To check if a variable or result is null or empty we compare it with the $null variable. The $null variable must be on the left side, to make sure that PowerShell compares the value correctly.
🌐
ServerMania
servermania.com › home › how to › software setup › how to use powershell not equal (-ne) operator: examples and best practices
PowerShell Not Equal (-ne) Operator Tutorial | ServerMania
August 26, 2025 - To find out whether the values of $a and $b are equal or not, use the PowerShell Not Equal comparison: ... Since $a has a value of 1 and $b of 2, which are not equal, the result is True. Given that the values of $c and $d are equal (3=3), the console will return True output, as displayed in the image above. ... Also, compare variables $c and $d to determine if they are not equal.
Top answer
1 of 8
1

The problem is here:

$UserPref = if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}

You’re doing a comparison on the $UserPref variable which has not been set because the comparison is in the assignment statement. This is not technically illegal, but you have strict mode on which will throw an error when you reference a variable that hasn’t been initiated. You can avoid this error by skipping the Set-StrictMode cmdlet.

However, the way you are assigning the $UserPref variable seems a bit wonky to me. It looks like you’re trying to check if it’s already set and then set some other variable values based on this comparison. Since each action you’re taking in the if construct is an assignment, there is no need to encapsulate those in the $UserPref assignment. Also, instead of checking for -eq $null in the if condition, you could just check for the existence of $UserPref:

if (!$UserPref){$UserPref = $UserGN}
2 of 8
5

I know I’m going to be kicking myself, but since I still consider myself a n00b with PS, I’ll try not to kick too hard.

I’ve got a script for new hires that works intermittently. HR insists that AD accounts use a person’s legal name, however many people prefer their nicknames for their email and display names, so a PreferredName field was created in HRIS. I’m checking for a preferred name ($UserPref) and if it exists I assign it to $UserPrefN and if it doesn’t, I assign their first name ($UserGN) to $UserPrefN. If $UserPref is blank ($null), sometimes it works and sometimes it doesn’t, lately more often than not it doesn’t and $UserPrefN doesn’t get set. It’s got to be my syntax, but I don’t see it.

[PS] C:\Windows\system32>Set-Strictmode -Version Latest -Verbose
[PS] C:\Windows\system32>$User = 'AccountName'
[PS] C:\Windows\system32>$UserSN = 'LastName'
[PS] C:\Windows\system32>$UserGN = 'FirstName'
[PS] C:\Windows\system32>$UserFI = $UserGN.substring(0,1)
[PS] C:\Windows\system32>$UserPref =
>> if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
>>
The variable '$UserPref' cannot be retrieved because it has not been set.
At line:2 char:5
+ if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
+     ~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (UserPref:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

[PS] C:\Windows\system32>
[PS] C:\Windows\system32>echo $UserPrefN
The variable '$UserPrefN' cannot be retrieved because it has not been set.
At line:1 char:6
+ echo $UserPrefN
+      ~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (UserPrefN:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

🌐
Computer Performance
computerperformance.co.uk › home › powershell
PowerShell Basics: If -And & If -Or Statements | Examples
January 9, 2019 - Fortunately, SolarWinds have created a Free WMI Monitor for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts. Take the guesswork out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free. ... Here is an example using logic to check whether you have a standard installation of your Microsoft Windows operating system. Clear-Host If ($env:SystemDrive -eq "C:" -And $env:SystemRoot -eq "C:\Windows") { "This looks like a standard Windows installation"} Else { "Non standard Windows installation" }
🌐
O'Reilly
oreilly.com › library › view › mastering-windows-powershell › 9781782173557 › ch03s02.html
Equal and not equal comparison - Mastering Windows PowerShell Scripting [Book]
April 27, 2015 - A script that shows how to use equal comparison operators would look like this: $value1 = "PowerShell" $value2 = "PowerShell" if ($value1 –eq $value2) { Write-Host "It's Equal!" }
Author   Brenton J.W. Blawat
Published   2015
Pages   282
🌐
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.
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › powershell operators › powershell comparison operators: an essential guide
PowerShell Comparison Operators: An Essential Guide - SharePoint Diary
December 3, 2025 - If the values are equal, the expression will evaluate to $true; otherwise, it will evaluate to $false. PowerShell includes several types of comparison operators, each with its own syntax and purpose.
🌐
PowerShell Forums
forums.powershell.org › powershell help
If A or B equals C - PowerShell Help - PowerShell Forums
August 20, 2019 - Hi All, I was writing a function today where I need the outcome to be true if A or B equal C, where see is the results of a Get-ItemProperty Originally I had: If $a -eq Get-ItemProperty… Of course in order to avoid running the Get-ItemProperty cmdlet twice (due to needing to comapre it against $b as well) I have assigned the results to variable $C for use in the if statement.
🌐
Reddit
reddit.com › r/powershell › strange way to write an if-check on a boolean
r/PowerShell on Reddit: Strange way to write an if-check on a boolean
September 18, 2023 -

Source: https://github.com/Esri/arcgis-powershell-dsc/blob/main/Modules/ArcGIS/ArcGIS.psm1

Lines 1953 and 1973 specifically.

I am looking at some powershell code (link above), and don't understand why a simple boolean check is written as:

$JobFlag = $True
# more code here...
if ($JobFlag[$JobFlag.Count - 1] -eq $True) { # CODE HERE }

There are some functions that might be called before the if-statement, but as far as I can tell, they return either $True or $False

Is there any reason for not writing a plain:

if ($JobFlag -eq $True)

I am by now means an experienced powershell user, therefore curious.