如何检查字符串在 PowerShell 中是否不为 NULL 或 EMPTY
- 使用条件语句检查 PowerShell 中的字符串变量是否不为 null 或空
-
使用
IsNullorEmpty
方法检查 PowerShell 中的字符串变量是否不为 null 或空 -
使用
IsNullOrWhiteSpace
方法检查 PowerShell 中的字符串变量是否不为 null 或空 -
使用
$null
变量检查 PowerShell 中的字符串变量是否不为 null 或空

字符串是用于表示文本的字符序列。您可以在 PowerShell 中使用单引号或双引号定义字符串。
在 PowerShell 中处理字符串变量时,有时您可能需要检查字符串变量是否是 null 或空。本教程将介绍检查字符串变量是否不为 null 或空的不同方法。
使用条件语句检查 PowerShell 中的字符串变量是否不为 null 或空
我们创建了一个字符串变量,$string
。
$string = "Hello World"
以下示例检查 PowerShell 中的 $string
变量是否为 null。如果变量不为 null 或空,则返回第一个语句;如果变量为 null 或空,则返回第二个语句。
if ($string) {
Write-Host "The variable is not null."
}
else {
Write-Host "The variable is null."
}
输出:
The variable is not null.
让我们给一个变量分配一个空字符串值并再次检查。如果一个变量没有被赋值,它也具有 null 值。
$string = ""
if ($string) {
Write-Host "The variable is not null."
}
else {
Write-Host "The variable is null."
}
输出:
The variable is null.
空格字符不被视为 null 字符串值。
使用 IsNullorEmpty
方法检查 PowerShell 中的字符串变量是否不为 null 或空
您可以使用 .NET 类 System.String
来检查 PowerShell 中的字符串变量是否为 null 或空。IsNullorEmpty()
方法指示指定的字符串是否为空或 null。
如果字符串为空,则返回 True
;如果不为空,则返回 False
。
[string]::IsNullOrEmpty($new)
输出:
True
现在,给变量分配一个字符串值。
$new = "asdf"
[string]::IsNullOrEmpty($new)
输出:
False
使用 IsNullOrWhiteSpace
方法检查 PowerShell 中的字符串变量是否不为 null 或空
您还可以使用 IsNullOrWhiteSpace
方法检查 PowerShell 中的字符串变量是否不为 null 或空。此方法仅适用于 PowerShell 3.0 及以上版本。
如果变量为 null、空或包含空格字符,则返回 True
;否则,在输出中打印 False
。
[string]::IsNullOrWhiteSpace($str)
输出:
True
给变量分配一个字符串值。
$str = "Have a nice day."
[string]::IsNullOrWhiteSpace($str)
输出:
False
使用 $null
变量检查 PowerShell 中的字符串变量是否不为 null 或空
$null
是 PowerShell 中的一个自动变量,表示 NULL。您可以使用 -eq
参数来检查字符串变量是否等于 $null
。
如果变量等于 $null
,则返回 True
;如果变量不等于 $null
,则返回 False
。
$str -eq $null
输出:
False
我们可以使用上述任何方法,轻松判断 PowerShell 中的字符串变量是否不为 null 或空。