在PowerShell中检查字符串是否非NULL或空

您所在的位置:网站首页 string判断非空 在PowerShell中检查字符串是否非NULL或空

在PowerShell中检查字符串是否非NULL或空

2024-07-03 16:27| 来源: 网络整理| 查看: 265

使用条件语句在PowerShell中检查字符串变量是否非NULL或空 使用 .NET 类 System.String 在PowerShell中检查字符串变量是否非NULL或空 使用 IsNullOrWhiteSpace 方法在PowerShell中检查字符串变量是否非NULL或空 使用 $null 变量在PowerShell中检查字符串变量是否非NULL或空

字符串是用于表示文本的字符序列。您可以在PowerShell中使用单引号或双引号来定义字符串。

在使用PowerShell中的字符串变量时,有时您可能需要检查字符串变量是否为 null 或为空。本教程将介绍在PowerShell中检查字符串变量是否非NULL或空的不同方法。

使用条件语句在PowerShell中检查字符串变量是否非NULL或空

我们创建了一个字符串变量 $string。

$string = "Hello World"

以下示例检查 $string 变量在PowerShell中是否为NULL。如果变量不为NULL或空,则返回第一个语句,如果变量为NULL或空,则返回第二个语句。

if ($string) { Write-Host "The variable is not null." } else{ Write-Host "The variable is null." }

输出:

The variable is not null.

让我们为变量分配一个空字符串值并再次检查。如果未分配变量,则它也具有空值。

$string="" if ($string) { Write-Host "The variable is not null." } else{ Write-Host "The variable is null." }

输出:

The variable is null.

空格字符不被视为空字符串值。

使用 .NET 类 System.String 在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,否则返回 False。

$str -eq $null

输出:

False

我们可以使用上述任何方法,轻松确定PowerShell中的字符串变量是否非NULL或空。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3