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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13738634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:46:44  来源:igfitidea点击:

How can I check if a string is null or empty in PowerShell?

.netstringpowershellnull

提问by pencilCake

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell?

IsNullOrEmpty在 PowerShell 中是否有内置的类似函数来检查字符串是 null 还是空?

I could not find it so far and if there is a built-in way, I do not want to write a function for this.

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

回答by Keith Hill

You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

你们这太难了。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

回答by Shay Levy

You can use the IsNullOrEmptystatic method:

您可以使用IsNullOrEmpty静态方法:

[string]::IsNullOrEmpty(...)

回答by Roman Kuzmin

In addition to [string]::IsNullOrEmptyin order to check for null or empty you can cast a string to a Boolean explicitly or in Boolean expressions:

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

$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" }

Output:

输出:

False
string is null or empty

False
string is null or empty

True
string is not null or empty

回答by Rubanov

If it is a parameter in a function, you can validate it with ValidateNotNullOrEmptyas you can see in this example:

如果它是函数中的参数,您可以使用ValidateNotNullOrEmpty以下示例对其进行验证:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}

回答by Nico van der Stok

Personally, I do not accept a whitespace ($STR3) as being 'not empty'.

就个人而言,我不接受空格 ($STR3) 为“非空”。

When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.

当一个只包含空格的变量传递给一个参数时,经常会出错,参数值可能不是'$null',而不是说它可能不是一个空格,一些remove命令可能会删除一个根文件夹而不是一个subfolder 如果子文件夹名称是“空格”,则在许多情况下不接受包含空格的字符串的所有原因。

I find this is the best way to accomplish it:

我发现这是实现它的最佳方法:

$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}

Empty

空的

$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}

Empty

空的

$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}

Empty!! :-)

空的!!:-)

$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}

Not empty

不是空的

回答by mhenry1384

I have a PowerShell script I have to run on a computer so out of date that it doesn't have [String]::IsNullOrWhiteSpace(), so I wrote my own.

我有一个 PowerShell 脚本,我必须在一台计算机上运行它,所以它已经过时了,它没有 [String]::IsNullOrWhiteSpace(),所以我自己写了。

function IsNullOrWhitespace($str)
{
    if ($str)
    {
        return ($str -replace " ","" -replace "`t","").Length -eq 0
    }
    else
    {
        return $TRUE
    }
}

回答by Skatterbrainz

# cases
$x = null
$x = ''
$x = ' '

# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}

回答by Nikolay Polyagoshko

PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace()is string -notmatch "\S"

PowerShell 2.0 替代[string]::IsNullOrWhiteSpace()string -notmatch "\S"

("\S" = any non-whitespace character)

(" \S" = 任何非空白字符)

> $null  -notmatch "\S"
True
> "   "  -notmatch "\S"
True
> " x "  -notmatch "\S"
False

Performance is very close:

性能非常接近:

> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
TotalMilliseconds : 3641.2089

> Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
TotalMilliseconds : 4040.8453

回答by Ryan

Another way to accomplish this in a pure PowerShell way would be to do something like this:

以纯 PowerShell 方式完成此操作的另一种方法是执行以下操作:

("" -eq ("{0}" -f $val).Trim())

This evaluates successfully for null, empty string, and whitespace. I'm formatting the passed value into an empty string to handle null (otherwise a null will cause an error when the Trim is called). Then just evaluate equality with an empty string. I think I still prefer the IsNullOrWhiteSpace, but if you're looking for another way to do it, this will work.

这将成功评估 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

In a fit of boredom, I played with this some and made it shorter (albeit more cryptic):

在一阵无聊中,我玩了一些并缩短了它的时间(尽管更神秘):

!!(("$val").Trim())

or

或者

!(("$val").Trim())

depending on what you're trying to do.

取决于你想做什么。

回答by Steve Friedl

Note that the "if ($str)"and "IsNullOrEmpty"tests don't work comparably in all instances: an assignment of $str=0produces false for both, and depending on intended program semantics, this could yield a surprise.

请注意,"if ($str)""IsNullOrEmpty"测试并非在所有情况下都具有可比性:$str=0两者的赋值都会产生错误,并且根据预期的程序语义,这可能会产生意外。