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

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


当前回答

为了解决@KeithHill的回答不包含IsNullOrWhitespace的问题,在PowerShell 7.1及以后版本中,我们可以使用空条件成员操作符来检查字符串是否为空或空白,而不需要首先检查字符串是否为$null,同时避免使用[string]::IsNullOrWhitespace(string)。

注意:如果你启用PSNullConditionalOperators实验特性,你也可以在PowerShell 7.0中做到这一点: Enable-ExperimentalFeature -Name PSNullConditionalOperators

使用Keith回答中的$str3示例(为了清晰起见,假装三元操作符在7.0之后就不存在了):

$str3 = ' '
if ( ${str3}?.Trim() ) {
  'not empty or whitespace'
} else {
  'empty or whitespace'
}
empty or whitespace

. trim()只在$str3是非空值时调用,否则返回$null。


有一件事要记住,那是一个问号吗?作为变量名的一部分有效。这就是为什么我们必须在应用条件访问操作符之前消除变量名的歧义:${str3}


因为我在前面提到了三元运算符,而且这个答案已经围绕PowerShell 7.1及以后的版本进行,所以你可以通过使用三元运算符来简化上面的代码块,几乎完全删除样板if/then/else语句:

${str3}?.Trim() ? 'not empty or whitespace' : 'empty or whitespace'

三元运算符是用于基本条件的简化if/then/else语句。我不想在这里用细微的差别把水搅浑了,而是把它理解为“如果左边唯一的问号?”为true,则执行?右边的内容,否则执行冒号后面的内容:"。

您可以在PowerShell文档中阅读关于三元运算符的更多信息。

其他回答

你们把事情搞得太复杂了。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

除了[string]::IsNullOrEmpty之外,为了检查null或空,您可以显式地将字符串强制转换为布尔值或布尔表达式:

$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" }

输出:

False
string is null or empty

False
string is null or empty

True
string is not null or empty

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

你可以使用IsNullOrEmpty静态方法:

[string]::IsNullOrEmpty(...)

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

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

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