Thursday, 16 April 2015

PowerShell - Testing if a String is NULL or EMPTY

Checking if a string is NULL or EMPTY is very common requirement in Powershell script. If we do not checked that we will get some unwanted results when we try to perform some operation on that string variable which is empty or null.

The following method is used to check if a string is NULL or empty.
$mystring ='hello'
if($mystring) {            
    Write-Host "Your string is not EMPTY"            
} else {            
    Write-Host "Your string is EMPTY or NULL"            
}
We can also use the .NET Class “System.String” to check null or empty string. It has a method IsNullOrEmpty() which returns true if the passed string is null or empty. Check the below example.
$mystring ='hello'
IF([string]::IsNullOrEmpty($mystring)) {            
    Write-Host "Your string is EMPTY or NULL"            
} else {            
    Write-Host "Your string is not EMPTY"            
}
We can also use the method IsNullOrWhiteSpace() from “System.String” class to detect a given string is NULL or EMPTY and whether it has WHITESPACE.
$mystring = " "            
IF([string]::IsNullOrWhiteSpace($mystring)) {            
    Write-Host "Your string is NULL or EMPTY or it has WHITESPACE"            
} else {            
    Write-Host "Your string is not EMPTY"            
}     
Note: The method IsNullOrWhiteSpace() is available only from .NET Frmaework 4.0, so, this method do not work in Powershell 2.0 and it will work only from Powershell 3.0.

You will get below error, when you run this method in Powershell 2.0.

IsNullOrWhitespace : Method invocation failed because [System.String] doesn’t contain a method named ‘IsNullOrWhiteSpace’

Advertisements
Advertisements

No comments:

Post a Comment