![]() |
卖萌的沙发 · mysql递归查询-腾讯云开发者社区-腾讯云· 8 月前 · |
![]() |
帅气的电影票 · OpenFileMappingW 函数 ...· 1 年前 · |
![]() |
奔放的楼房 · python 如何绘制分叉图-阿里云开发者社区· 2 年前 · |
![]() |
活泼的领结 · 「linux获取时间」相关问答|文档|产品| ...· 2 年前 · |
![]() |
独立的灭火器 · 那些年我们遇到的坑(3)-basePacka ...· 2 年前 · |
在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