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

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

    PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace() is string -notmatch "\S"

    ("\S" = any non-whitespace character)

    > $null  -notmatch "\S"
    True
    > "   "  -notmatch "\S"
    True
    > " x "  -notmatch "\S"
    False
    

    Performance is very close:

    > Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
    TotalMilliseconds : 3641.2089
    
    > Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
    TotalMilliseconds : 4040.8453
    

提交回复
热议问题