PowerShell: Determine if string is null or is empty

PowerShell makes it easy to check if a string is null or empty.  You use if (string) else.

Setting your string variable to $null gives you an empty string:

$mystringvar = $null
if ($mystringvar) { "It is empty" } else { "It is not empty" }

Result: It is empty

$mystringvar = ""
if ($mystringvar) { "It is empty" } else { "It is not empty" }

Result: It is empty

$mystringvar = "This string has text"
if ($mystringvar) { "It is empty" } else { "It is not empty" }

Result: It is not empty

 

 

Comments are closed.