Check if String Is Empty in PowerShell

PowerShell is a cross-platform automation tool used as a command-line console, a scripting language, and a configuration management system for CI/CD pipeline systems. More details about PowerShell is in this link.
IsNullOrEmpty
is a common scripting/programming language, a string method for checking whether a given string is empty
or null
. A null
is a string value that has not been assigned, and an empty
string is a string with " "
or given String.Empty
.
Read more about IsNullOrEmpty
method at this site.
In PowerShell, there is a way to do this. We will discuss it through this article.
IsNullOrEmpty
Alternatives to Check if a String Is Null or Empty in PowerShell
There is an easy way to do PowerShell’s IsNullOrEmpty
equivalent function.
The following code segments can be used.
PS C:\Users\Test> $str1 = $null
PS C:\Users\Test> if ($str1) { 'not empty' } else { 'empty' }
The string given in the command is null
. Therefore, the output of the above code is as below.
PS C:\Users\Test> $str1 = $null
PS C:\Users\Test> if ($str1) { 'not empty' } else { 'empty' }
empty
If the string is empty
, then the output given is still empty
.
PS C:\Users\Test> $str2 = ''
PS C:\Users\Test> if ($str2) { 'not empty' } else { 'empty' }
empty
If the string is not empty
and not null
, the output given is not empty
.
PS C:\Users\Test> $str3 = ' '
PS C:\Users\Test> if ($str3) { 'not empty' } else { 'empty' }
not empty
There are commands to compare two strings and check whether two or more are empty
.
PS C:\Users\Agni> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty'}
one or both empty
The output of the above code is one or both empty
.
Further, neither empty
is also one possible comparative used above to compare two declared strings.
This can be identified as the clearest and the most concise method of using the IsNullOrEmpty
Other than the above method, IsNullOrEmpty
static method can also be used in the PowerShell.
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
Related Article - PowerShell String
- Array of Strings in PowerShell
- Check if a File Contains a Specific String Using PowerShell
- Extract a PowerShell Substring From a String
- Extract Texts Using Regex in PowerShell
- Generate Random Strings Using PowerShell
- Escape Single Quotes and Double Quotes in PowerShell