在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?

到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。


当前回答

您可以创建一个过滤器,将空字符串转换为null,然后只需检查是否为null。

filter nullif {@($_, $null)[$_ -eq '']}

然后你只需要将你的价值注入其中

('' | nullif) -eq $null
> True
('x' | nullif) -eq $null
> False

一个更简单的方法是使用正则表达式

$null -match '^$'
> True
'' -match '^$'
> True
'x' -match '^$'
> False

其他回答

你可以使用IsNullOrEmpty静态方法:

[string]::IsNullOrEmpty(...)

您可以创建一个过滤器,将空字符串转换为null,然后只需检查是否为null。

filter nullif {@($_, $null)[$_ -eq '']}

然后你只需要将你的价值注入其中

('' | nullif) -eq $null
> True
('x' | nullif) -eq $null
> False

一个更简单的方法是使用正则表达式

$null -match '^$'
> True
'' -match '^$'
> True
'x' -match '^$'
> False

PowerShell 2.0替换[string]::IsNullOrWhiteSpace()是字符串-notmatch "\S"

("\S" =任何非空白字符)

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

性能非常接近:

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

> Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
TotalMilliseconds : 4040.8453

凯斯·希尔(Keith Hill)的回答(为了解释空白)的延伸:

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

对于空字符、空字符串和有空格的字符串,返回“Empty”,对于其他所有字符,返回“Not Empty”。

你们把事情搞得太复杂了。PowerShell非常优雅地处理了这个问题,例如:

> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty