Checking for NULL in PS

This topic contains 6 replies, has 4 voices, and was last updated by  Ramon Tan 2 weeks ago.

  • Author
  • #103867

    Ramon Tan

    Hello Scripting Experts,

    I have extracted a simple file via the Import-Excel command as follows:
    > Import-Excel $infile -Noheader -Dataonly -Startrow 2 | Select P2,P3,P4,P5 |
    Foreach-Object { If ($_.P2 = NULL ???) ...

    My objective is to check the property P2 for a NULL (i.e., empty) value (not quite the same as blanks).
    Will the following lines work: (the first line assigns to $Null the empty string using single-quote)
    $Null = "
    ForEach-Object { If (($_.P2 -EQ $Null) -EQ $True) { true branch } Else { ... }?

    Would be grateful for any tips, advice or suggestions.

  • #103873

    Olaf Soyk

    The variable $null already exists on Powershell ... always. You don't need to create or assign. If you like to check for $null you can simply do

    if ($_.P2 -eq $null) {....}
    • #103990

      Ramon Tan

      Many thanks, much appreciated.

  • #103888

    iain Barnetson

    I use this

  • #103993

    Joel Sallow

    One other possibility that is a little more a case-by-case basis is that you can use the fact that when cast to bool, $null becomes $false, and most other things that contain data become $true. So you can do:

    if (-not $_.P2) { 
    # code here 

    If $_.P2 is either $null, zero, a zero-length array, or contains the value $false, the if statement would execute. Just about anything else is $true and would skip the code in the script block.

    • #104006

      iain Barnetson

      "If $_.P2 is either $null, zero, a zero-length array, or contains the value $false, the if statement would execute"
      But not if it's Whitespace.

      $P2 = "  "
      if ( -Not $P2) { 
      Write-Host "White space" 
      } else { Write-Host "something" }
      if([string]::IsNullOrWhiteSpace($P2)) { 
      Write-Host "White space"
      } else { Write-Host  "something" }
  • #104011

    Ramon Tan

    Thank you all Messrs. Barnetson, Sallow and Soyk. Your replies shed a lot of light and provide many interesting highlights. I have performed your examples hands-on, and I am extremely grateful for your posts. In the course of my "immersion" with NULL, I came across a very informative and interesting site/post, with a short article on the same subject:
    I thought it interesting to extract that portion of the article to share this author's "all in one" NULL function:
    function IsNull($objectToCheck) {
    if ($objectToCheck -eq $null) { return $true }

    if ($objectToCheck -is [String] -and $objectToCheck -eq [String]::Empty) { return $true }

    if ($objectToCheck -is [DBNull] -or $objectToCheck -is [System.Management.Automation.Language.NullString]) { return $true }
    return $false
    Sincerest thanks to you all for sharing your expertise.

You must be logged in to reply to this topic.