Powershell:- Is String Variable Null?

Background

Let us do a very quick exercise.

The exercise will be to validate whether a variable’s content is null.

 

Code

Script


Set-StrictMode -Version Latest

[string]  $day = $null;
[string]  $typeOfTest = "";
[Boolean] $bTestResult = $false;
[string]  $FORMAT_TEST_RESULT = "Type of Test - {0} - Result is {1}";

<#
	variable -eq null
#>
$typeofTest = "variable -eq `$null";

$bTestResult = ($day -eq $null);

$log = $FORMAT_TEST_RESULT -f $typeofTest, $bTestResult;

Write-Host $log;


<#
	null -eq variable
#>
$typeofTest = "`$null -eq variable";

$bTestResult = ($null -eq $day);

$log = $FORMAT_TEST_RESULT -f $typeofTest, $bTestResult;

Write-Host $log;


<#
	variable -eq ""
#>
$typeofTest = "variable -eq `"`"";

$bTestResult = ($day -eq "");

$log = $FORMAT_TEST_RESULT -f $typeofTest, $bTestResult;

Write-Host $log;


<#
	variable -eq ''
#>
$typeofTest = "variable -eq ''";

$bTestResult = ($day -eq '');

$log = $FORMAT_TEST_RESULT -f $typeofTest, $bTestResult;

Write-Host $log;



<#
	 [string]::IsNullOrEmpty(variable)
#>
$typeofTest = "[string]::IsNullOrEmpty(variable)";

$bTestResult = ( [string]::IsNullOrEmpty($day));

$log = $FORMAT_TEST_RESULT -f $typeofTest, $bTestResult;

Write-Host $log;


 

Output

Output – Image

Output – Text


>powershell -file isDayNull.ps1
Type of Test - variable -eq $null - Result is False
Type of Test - $null -eq variable - Result is False
Type of Test - variable -eq "" - Result is True
Type of Test - variable -eq '' - Result is True
Type of Test -  [string]::IsNullOrEmpty(variable) - Result is True

>

Output – Explanation

Type of Test Test Test Result
variable -eq $null ($day -eq $null) False
$null -eq variable ($null -eq $day) False
variable -eq “” ($day -eq “”) True
variable -eq ” ($null -eq $day) True
[string]::IsNullOrEmpty(variable) [string]::IsNullOrEmpty($day) False

 

Source Code

  1. GitLab
    • Powershell – Null Tests
      • datatype.string.isDayNull.ps1
        Link

Summary

Our variable ( $day) is set to null.

Yet, Powershell does not store the string variable has null.

Null is stored as an empty string.

Checking the variable against $null, fails.

But, checking against the following succeeds:-

  1. Empty String using -eq operator
    • Empty String as double quotes ( “”)
    • Empty String as single ( “”)
  2. .Net String Class
  • Methods
      • IsNullOrEmpty

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s