我该如何在PowerShell中检查字符串是否为null或空?

27 浏览
0 Comments

我该如何在PowerShell中检查字符串是否为null或空?

PowerShell中是否有内置的IsNullOrEmpty函数用于检查字符串是否为null或空字符串?

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

admin 更改状态以发布 2023年5月21日
0
0 Comments

您可以使用 IsNullOrEmpty 静态方法:

[string]::IsNullOrEmpty(...)

0
0 Comments

你们把这个问题看得太复杂了。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

0