Powershell command - null or empty comand is not working

aditya dugyala 1 Reputation point
2021-08-13T16:45:58.97+00:00

Tried both the cases to check if it is nullorempty but eventhough its null the statement is passing
$RequestorEmail=""

case1
if(($RequestorEmail -ne $null) -or ($RequestorEmail -ne ""))

case2
if ( -not [string]::IsNullOrEmpty( $RequestorEmail ) )

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-08-13T16:58:55.733+00:00

    Hi @aditya dugyala ,

    maybe this helps:

    $a = ""  
    if ($a) {   
        Write-Output "variable contains value"   
    }  
    else {   
        Write-Output "variable is empty"  
    }  
    

    Or vice versa:

    $a = ""  
    if (!$a) {      
        Write-Output "variable is empty"  
    }  
    else {   
        Write-Output "variable contains value"  
    }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

  2. Rich Matheisen 47,901 Reputation points
    2021-08-13T19:30:52.917+00:00

    In the situation you present, $RequestorEmail contains an empty string.

    In your 1st test, since the variable $RequestorEmail is NOT $null (because it holds an empty string), and the string DOES contain an empty string, both conditions fail so the result is FALSE.

    In your 2nd test, the variable $RequestorEmail IS empty and the IsNullOrEmpty is true, but you're negating that with the -not operator, so the result is FALSE.

    What results where you expecting? And why?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.