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

后端 未结 11 1032
没有蜡笔的小新
没有蜡笔的小新 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 05:05

    In addition to [string]::IsNullOrEmpty in order to check for null or empty you can cast a string to a Boolean explicitly or in Boolean expressions:

    $string = $null
    [bool]$string
    if (!$string) { "string is null or empty" }
    
    $string = ''
    [bool]$string
    if (!$string) { "string is null or empty" }
    
    $string = 'something'
    [bool]$string
    if ($string) { "string is not null or empty" }
    

    Output:

    False
    string is null or empty
    
    False
    string is null or empty
    
    True
    string is not null or empty
    

提交回复
热议问题