在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
当前回答
除了[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
您可以创建一个过滤器,将空字符串转换为null,然后只需检查是否为null。
filter nullif {@($_, $null)[$_ -eq '']}
然后你只需要将你的价值注入其中
('' | nullif) -eq $null
> True
('x' | nullif) -eq $null
> False
一个更简单的方法是使用正则表达式
$null -match '^$'
> True
'' -match '^$'
> True
'x' -match '^$'
> False
# cases
$x = null
$x = ''
$x = ' '
# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
在纯PowerShell中完成这一任务的另一种方法是这样做:
("" -eq ("{0}" -f $val).Trim())
此方法成功计算null、空字符串和空白。我正在将传递的值格式化为空字符串以处理null(否则null将在调用Trim时导致错误)。然后用空字符串求相等值。我想我仍然更喜欢IsNullOrWhiteSpace,但如果您正在寻找另一种方法来实现它,那么这个方法也可以。
$val = null
("" -eq ("{0}" -f $val).Trim())
>True
$val = " "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False
在一阵无聊中,我玩了一些,并把它缩短了(尽管更神秘):
!!(("$val").Trim())
or
!(("$val").Trim())
这取决于你想做什么。
我有一个PowerShell脚本,我必须在一台过时的计算机上运行,它没有[String]::IsNullOrWhiteSpace(),所以我自己写了一个。
function IsNullOrWhitespace($str)
{
if ($str)
{
return ($str -replace " ","" -replace "`t","").Length -eq 0
}
else
{
return $TRUE
}
}