在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
当前回答
就我个人而言,我不接受空格($STR3)为“非空”。
当一个只包含空白的变量被传递到一个参数时,通常会错误地认为参数值可能不是'$null',而不是说它可能不是一个空白,一些删除命令可能会删除一个根文件夹而不是子文件夹,如果子文件夹名称是“空白”,所有的原因是在许多情况下不接受包含空白的字符串。
我发现这是最好的方法:
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
空
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
空
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
空! !: -)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
非空
其他回答
另一种选择是向系统中添加2个新的脚本方法。使用Update-TypeData的字符串实例:
Update-TypeData -MemberType ScriptMethod -MemberName IsNullOrEmpty -Value {
return [string]::IsNullOrEmpty($this)
} -TypeName System.String
Update-TypeData -MemberType ScriptMethod -MemberName IsNullOrWhiteSpace -Value {
return [string]::IsNullOrWhiteSpace($this)
} -TypeName System.String
'hello'.IsNullOrEmpty() # => False
''.IsNullOrEmpty() # => True
' '.IsNullOrEmpty() # => False
' '.IsNullOrWhiteSpace() # => True
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
凯斯·希尔(Keith Hill)的回答(为了解释空白)的延伸:
$str = " "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
对于空字符、空字符串和有空格的字符串,返回“Empty”,对于其他所有字符,返回“Not Empty”。
你们把事情搞得太复杂了。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
除了[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