在PowerShell中,有没有内置的IsNullOrEmpty
-like函数来检查字符串是空的还是空的?
到目前为止,我找不到它,如果有内置的方法,我不想为此编写函数。
发布于 2012-12-06 15:48:30
您可以使用IsNullOrEmpty
静态方法:
[string]::IsNullOrEmpty(...)
发布于 2012-12-07 00:21:38
你们把事情搞得太复杂了。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
发布于 2012-12-06 16:30:54
除了[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
https://stackoverflow.com/questions/13738634
复制相似问题