首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在PowerShell中检查字符串是否为null或空?

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

Stack Overflow用户
提问于 2012-12-06 15:09:29
回答 12查看 656.1K关注 0票数 496

在PowerShell中,有没有内置的IsNullOrEmpty-like函数来检查字符串是空的还是空的?

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

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2012-12-06 15:48:30

您可以使用IsNullOrEmpty静态方法:

代码语言:javascript
运行
复制
[string]::IsNullOrEmpty(...)
票数 575
EN

Stack Overflow用户

发布于 2012-12-07 00:21:38

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

代码语言:javascript
运行
复制
> $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
票数 693
EN

Stack Overflow用户

发布于 2012-12-06 16:30:54

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

代码语言:javascript
运行
复制
$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" }

输出:

代码语言:javascript
运行
复制
False
string is null or empty

False
string is null or empty

True
string is not null or empty
票数 50
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13738634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档