You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

Copy> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty
Answer from Keith Hill on Stack Overflow
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to check for null, not null, or empty in powershell?
How to Check for Null, Not Null, or Empty in PowerShell? - SharePoint Diary
September 28, 2025 - The following code snippet shows ... not null - example $var = "Hello, world!" if ($var -ne $null) { Write-Host "The variable is not null." } else { Write-Host "The variable is null."...
Discussions

powershell - Check if a string is not NULL or EMPTY - Stack Overflow
You can use the [string]::IsNullOrEmpty($version) method if it is a string. But, I was looking for a universal way to check nulls (regardless of data type) in Powershell. Checking for null (or not null) values in PowerShell is tricky. Using ($value -eq $null) or ($value -ne $null) does not ... More on stackoverflow.com
🌐 stackoverflow.com
Checking for NULL in PS
Hello Scripting Experts, I have extracted a simple file via the Import-Excel command as follows: > Import-Excel $infile -Noheader -Dataonly -Startrow 2 | Select P2,P3,P4,P5 | Foreach-Object { If ($_.P2 = NULL ???) … My objective is to check the property P2 for a NULL (i.e., empty) value (not ... More on forums.powershell.org
🌐 forums.powershell.org
6
0
July 4, 2018
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
how to check a value is that null in powershell script
I want to check the PasswordLastSet value of the user is that empty. PS Z:\> Get-ADUser -Identity test1 -Properties * | select passwordlastset passwordlastset --------------- By if to judgment is that null. this is my script $password =… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
September 10, 2020
🌐
LazyAdmin
lazyadmin.nl › home › powershell – check if variable is null or empty
PowerShell - Check if variable is Null or Empty — LazyAdmin
April 9, 2024 - But when you place $null it on the right-hand side, then it will return everything from the array, that does not equal $null. If you are using PowerShell 7, and you actually should, then you can use one of the new null conditional operators to quickly check if a variable or property is null or not.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › scripting › learn › deep-dives › everything-about-null
Everything you wanted to know about $null - PowerShell | Microsoft Learn
June 11, 2024 - There are some scenarios where placing it on the right doesn't give you the expected result. Look at this next example and try to predict the results: if ( $value -eq $null ) { 'The array is $null' } if ( $value -ne $null ) { 'The array is not ...
🌐
PowerShell Forums
forums.powershell.org › powershell help
Checking for NULL in PS - PowerShell Help - PowerShell Forums
July 4, 2018 - Hello Scripting Experts, I have extracted a simple file via the Import-Excel command as follows: > Import-Excel $infile -Noheader -Dataonly -Startrow 2 | Select P2,P3,P4,P5 | Foreach-Object { If ($_.P2 = NULL ???) … My objective is to check the property P2 for a NULL (i.e., empty) value (not quite the same as blanks).
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

Find elsewhere
🌐
ShellGeek
shellgeek.com › home › powershell › powershell $null – check for null
PowerShell $null - Check for null - ShellGeek
April 14, 2024 - PowerShell $null is an automatic variable that represents null or absent. PowerShell $null, check if a variable is empty, or if not null.
🌐
Thomas Maurer
thomasmaurer.ch › home › powershell: check variable for null
Powershell: check variable for null - Thomas Maurer
December 21, 2020 - In addition, I am also going to share how you can use the Null conditional operators in PowerShell 7. PowerShell check variable for null The normal if -eq '$null' doesn't work: if ($varibalename -eq $null) { Write-Host 'variable is null' } Now ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 92154 › how-to-check-a-value-is-that-null-in-powershell-sc
how to check a value is that null in powershell script - Microsoft Q&A
September 10, 2020 - $password = Get-ADUser -Identity test1 -Properties * | select passwordlastset if ($password -ne $null){ Write-Output "It's empty" } else { Write-Output "It isn't empty" }
🌐
Java2Blog
java2blog.com › home › powershell › powershell – check if variable is null
PowerShell - Check If Variable Is Null [5 Ways] - Java2Blog
November 23, 2023 - In Powershell, $null is treated as an object with a value of null. It is singleton object, meaning there is only one instance of $null in PowerShell environment. The eq operator is the most straightforward and recommended method to check if ...
🌐
Reddit
reddit.com › r/powershell › help with if/else and null value
r/PowerShell on Reddit: Help With If/Else and Null Value
April 8, 2019 -

I'm troubleshooting a rebuild of my company's server build script and I'm trying to build logic into the script that acts based on whether a variable is null. We build different types of servers and I want the script to essentially create commands to be run later on in the script execution, but I don't want those commands to be created or run if the value of the variable given is null. Here's what I'm looking at (pardon this will be psuedo code and likely a bit sloppy:

$VMIP2 = Read-Host "Enter IP for $VM (x.x.x.x format)"
if ($VMIP2 -eq $null) Do nothing
if ($VMIP2 -eq "Any valid IP address") Create the following command as a variable:
$NewCommand = "New-NetIPAddress -InterfaceAlias "IntAlias" -IPAddress <IPAddress> -PrefixLength 24 -SkipAsSource $true"
else Write-Verbose "Input not valid, please re-enter $VMIP2"

I also want to do this with my $Domain variable, but instead creating the Add-Computer command. I have some users who are very Powershell illiterate and I'm trying to make the script as user-friendly as possible. Any and all help is always appreciated, thanks.

Top answer
1 of 5
8
Never execute commands from user string input carelessly inserted into strings. If the user decided to enter something like 1.1.1.1; remove-item c:\ -force -recurse at that prompt, you'd have a lot of fun recovering from that. Instead, pass the user input to the actual command call as a single value. $VMIP2 = Read-Host "Enter IP for $VM (x.x.x.x format)" if ($VMIP2 -as [ipaddress]) { $Command = { New-NetIPAddress -InterfaceAlias "IntAlias" -IPAddress $VMIP2 -PrefixLength 24 -SkipAsSource $true } } # Execute command script block with: & $Command This ensures that the user's value is treated as a literal string, instead of part of the command string. Any funny business will simply register as an invalid IP address. Note that storing the command script isn't needed if you're just going to execute it, but I put that in just as an aside to show that you can still do that safely. Personally, I'd prefer to write this script with parameters that can be entered when calling it, with the read-host only an as-needed backup (if it's there at all; usually I prefer to let it error out and the user can fix their own stuff). That looks like this: # this should be the first thing in the file. Add any other parameters with a comma between each. param( $VmIpAddress = (Read-Host "Enter IP for $VM (x.x.x.x format)") ) if ($VmIpAddress -as [ipaddress]) { $Command = { New-NetIPAddress -InterfaceAlias "IntAlias" -IPAddress $VmIpAddress -PrefixLength 24 -SkipAsSource $true } } # Execute command script block with: & $Command Note that -as is a soft-cast operator. It attempts to convert the value to the designated type. If it fails, it gives a $null value back, which the if statement treats the same as $false. If it succeeds, the if statement will treat it as $true instead.
2 of 5
3
I would check if it's not null/empty, if it matches the expected IP Input (x.x.x.x), and if it can be cast as an [ipaddress]. You could also just lookup valid IP Address regex and use that... but this is easier to understand IMO. $VMIP2 = Read-Host "Enter IP for $VM (x.x.x.x format)" if ( (-not [string]::IsNullOrWhiteSpace($VMIP2)) -and ($VMIP2 -match '\d+\.\d+\.\d+\.\d+') -and ($VMIP2 -as [ipaddress]) ) { "New-NetIPAddress -InterfaceAlias 'IntAlias' -IPAddress $VMIP2 -PrefixLength 24 -SkipAsSource $true" } else { "Input not valid, please re-enter `$VMIP2" }
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 513246 › powershell-command-null-or-empty-comand-is-not-wor
Powershell command - null or empty comand is not working - Microsoft Q&A
August 13, 2021 - case1 if(($RequestorEmail -ne $null) -or ($RequestorEmail -ne "")) case2 if ( -not [string]::IsNullOrEmpty( $RequestorEmail ) ) Windows for business | Windows Server | User experience | PowerShell
🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › powershell null
PowerShell null | How does $null Variable Works in PowerShell | Examples
March 6, 2023 - PowerShell treats $Null object with the value null and some commands require some output to generate and they generate value null if there is any error and can also be useful in the troubleshooting purpose in the scripts to check if the command generates any value.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Thinkpowershell
thinkpowershell.com › blog › test-powershell-variable-for-null-empty-string-and-white-space
Test PowerShell Variable for Null, Empty String, and White Space
October 25, 2017 - PS C:\> $Service = Get-CimInstance -ClassName Win32_Service -Filter "Name='AMD External Events Utility'" $Service.Description -eq "" -or $Service.Description -eq $null True · This works, but you have to always remember to code for two comparisons, and it is twice as much work as a single comparison. Luckily, there is a .NET String method we can take advantage of directly called IsNullOrEmpty. To use this within PowerShell, we type [string]::IsNullOrEmpty($variable) to use the .NET class’ method:
🌐
Powershellexplained
powershellexplained.com › 2018-12-23-Powershell-null-everything-you-wanted-to-know
Everything you wanted to know about $null - Powershell
December 23, 2018 - This is different then what you may expect if you come from another language. Any time you try to use a variable that you have not initialized with a value, it will be $null. This is one of the most common ways that $null values will sneak into your code. ... It you happen to mistype a variable name then PowerShell will see it as a different variable and the value will be $null. The other way you will find $null values is when they come from other commands that don’t give you any results.
🌐
PowerShell Test-Path
powershellfaqs.com › powershell-isnullorempty
PowerShell IsNullOrEmpty() Example
July 29, 2024 - Let me show you another example of how to validate user input using the IsNullOrEmpty() method in PowerShell. When writing scripts that require user input, it’s essential to validate that the input is neither null nor empty. Here’s how you can use [string]::IsNullOrEmpty to ensure valid ...
🌐
SPGuides
spguides.com › check-if-a-variable-is-null-or-empty-in-powershell
How to Check if a Variable is Null or Empty in PowerShell?
May 7, 2025 - The best way to check if a variable is null is to compare it directly with the $null special value in PowerShell.
🌐
Cody Konior
codykonior.com › 2013 › 10 › 17 › checking-for-null-in-powershell
Checking for null in PowerShell
October 17, 2013 - [string] $a = $null $a -eq $null # False $a -eq "" -and $a -eq [String]::Empty # True if (!$a) { Write-Host "True" } else { Write-Host "False" } # True · That is insidious because if you write a function that explicitly types its argument as [string] PowerShell will prevent you from passing in $null, always converting it to [String]::Empty.