How can I check if a string is null or empty in PowerShell?

后端 未结 11 1026
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 04:49

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell?

I could not find it so far and if there i

相关标签:
11条回答
  • 2020-12-02 04:50

    You can use the IsNullOrEmpty static method:

    [string]::IsNullOrEmpty(...)
    
    0 讨论(0)
  • 2020-12-02 04:50

    If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty as you can see in this example:

    Function Test-Something
    {
        Param(
            [Parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
            [string]$UserName
        )
    
        #stuff todo
    }
    
    0 讨论(0)
  • 2020-12-02 04:52

    Another way to accomplish this in a pure PowerShell way would be to do something like this:

    ("" -eq ("{0}" -f $val).Trim())
    

    This evaluates successfully for null, empty string, and whitespace. I'm formatting the passed value into an empty string to handle null (otherwise a null will cause an error when the Trim is called). Then just evaluate equality with an empty string. I think I still prefer the IsNullOrWhiteSpace, but if you're looking for another way to do it, this will work.

    $val = null    
    ("" -eq ("{0}" -f $val).Trim())
    >True
    $val = "      "
    ("" -eq ("{0}" -f $val).Trim())
    >True
    $val = ""
    ("" -eq ("{0}" -f $val).Trim())
    >True
    $val = "not null or empty or whitespace"
    ("" -eq ("{0}" -f $val).Trim())
    >False
    

    In a fit of boredom, I played with this some and made it shorter (albeit more cryptic):

    !!(("$val").Trim())
    

    or

    !(("$val").Trim())
    

    depending on what you're trying to do.

    0 讨论(0)
  • 2020-12-02 04:56

    I have a PowerShell script I have to run on a computer so out of date that it doesn't have [String]::IsNullOrWhiteSpace(), so I wrote my own.

    function IsNullOrWhitespace($str)
    {
        if ($str)
        {
            return ($str -replace " ","" -replace "`t","").Length -eq 0
        }
        else
        {
            return $TRUE
        }
    }
    
    0 讨论(0)
  • 2020-12-02 04:56

    An extension of the answer from Keith Hill (to account for whitespace):

    $str = "     "
    if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
    

    This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.

    0 讨论(0)
  • 2020-12-02 05:02

    Note that the "if ($str)" and "IsNullOrEmpty" tests don't work comparably in all instances: an assignment of $str=0 produces false for both, and depending on intended program semantics, this could yield a surprise.

    0 讨论(0)
提交回复
热议问题