http://techibee.com/powershell/check-if-a-string-is-null-or-empty-using-powershell/1889
Check If a string is NULL or EMPTY using PowerShell
by Techibee on October 10, 2012
In this post, I'll show you what to verify if a string is empty, null or have white spaces using Powershell.
Checking If a string is NULL or EMPTY is very common requirement in Powershell script. If we don ' t do, we'll end up with run time errors if we try to perform some operation on that string variable which is empty or null. So the question are, how to check it?
Well, below are the most often used technique to check if a string is NULL or empty
if ($mystring) {
Write-host "string is not empty"
} else {
Write-host "String is EMPTY or NULL"
}
Most scripts use this method, however we can make things better by using "System.String" dotnet class. It has a method IsNullOrEmpty () which returns true if the passed string is null or empty. See the below example for clarity
IF ([String]::isnullorempty ($mystring)) {
Write-host "Given string is NULL or EMPTY"
} else {
Write-host "Given string has a value"
}
Both the methods described above gives you the same functionality. But if you want more meaningful and neat look to your code, I would prefer the second method.
Now you might get a question, what if the $mystring have white space as value. It is neither a, EMPTY value nor a NULL value so we can not use IsNullOrEmpty () method in the this case. If you try it, it'll return False which means string is not NULL or EMPTY. In such cases we can use the another method available with System.String class. That is Isnullorwhitespace (). The good thing about this method was it covers all three cases, NULL, EMPTY, and whitespace. It'll work for any number whitespaces in the variable. See the below examples for clarity
IF ([String]::isnullorwhitespace ($string 1)) {
Write-host "Given string is NULL or has whitespace"
} else {
Write-host "Given string has a value"
}
$string 1 = ""
IF ([String]::isnullorwhitespace ($string 1)) {
Write-host "Given string is NULL or has whitespace"
} else {
Write-host "Given string has a value"
}
$string 1 = ""
IF ([String]::isnullorwhitespace ($string 1)) {
Write-host "Given string is NULL or has whitespace"
} else {
Write-host "Given string has a value"
}
After executing above code you'll get Given string is NULL or has whitespace three times in output. So, it was clear that Theisnullorwhitespace () method was working for detecting NULL, EMPTY and Whilespace strings.
Hope This helps and happy learning.
Please feel the free-to-write in comments sections if you have any questions
Check If a string is NULL or EMPTY using PowerShell