在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
在PowerShell中,是否有内置的isnullorempty类函数来检查字符串是否为空?
到目前为止我找不到它,如果有内置的方法,我不想为此写一个函数。
当前回答
可以同时使用IsNullOrWhitespace()和isNullOrEmpty()静态方法的条件语句来测试空白或空值。例如,在插入到MySQL数据库之前,我将遍历我将输入的值,并使用条件避免空值或空白值。
// RowData is iterative, in this case a hashtable,
// $_.values targets the values of the hashtable
```PowerShell
$rowData | ForEach-Object {
if(-not [string]::IsNullOrEmpty($_.values) -and
-not [string]::IsNullOrWhiteSpace($_.values)) {
// Insert logic here to use non-null/whitespace values
}
}
其他回答
如果它是一个函数中的参数,你可以用ValidateNotNullOrEmpty验证它,就像你在这个例子中看到的那样:
Function Test-Something
{
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
#stuff todo
}
你可以使用IsNullOrEmpty静态方法:
[string]::IsNullOrEmpty(...)
可以同时使用IsNullOrWhitespace()和isNullOrEmpty()静态方法的条件语句来测试空白或空值。例如,在插入到MySQL数据库之前,我将遍历我将输入的值,并使用条件避免空值或空白值。
// RowData is iterative, in this case a hashtable,
// $_.values targets the values of the hashtable
```PowerShell
$rowData | ForEach-Object {
if(-not [string]::IsNullOrEmpty($_.values) -and
-not [string]::IsNullOrWhiteSpace($_.values)) {
// Insert logic here to use non-null/whitespace values
}
}
除了[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
为了解决@KeithHill的回答不包含IsNullOrWhitespace的问题,在PowerShell 7.1及以后版本中,我们可以使用空条件成员操作符来检查字符串是否为空或空白,而不需要首先检查字符串是否为$null,同时避免使用[string]::IsNullOrWhitespace(string)。
注意:如果你启用PSNullConditionalOperators实验特性,你也可以在PowerShell 7.0中做到这一点: Enable-ExperimentalFeature -Name PSNullConditionalOperators
使用Keith回答中的$str3示例(为了清晰起见,假装三元操作符在7.0之后就不存在了):
$str3 = ' '
if ( ${str3}?.Trim() ) {
'not empty or whitespace'
} else {
'empty or whitespace'
}
empty or whitespace
. trim()只在$str3是非空值时调用,否则返回$null。
有一件事要记住,那是一个问号吗?作为变量名的一部分有效。这就是为什么我们必须在应用条件访问操作符之前消除变量名的歧义:${str3}
因为我在前面提到了三元运算符,而且这个答案已经围绕PowerShell 7.1及以后的版本进行,所以你可以通过使用三元运算符来简化上面的代码块,几乎完全删除样板if/then/else语句:
${str3}?.Trim() ? 'not empty or whitespace' : 'empty or whitespace'
三元运算符是用于基本条件的简化if/then/else语句。我不想在这里用细微的差别把水搅浑了,而是把它理解为“如果左边唯一的问号?”为true,则执行?右边的内容,否则执行冒号后面的内容:"。
您可以在PowerShell文档中阅读关于三元运算符的更多信息。