当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell $null - 检查 null

作者:精品下载站 日期:2024-12-14 16:39:57 浏览:15 分类:玩电脑

PowerShell $null - 检查 null


PowerShell $null 是一个自动变量,表示 null 或不存在。PowerShell $null 用作空占位符将其分配给变量,在比较中使用它。

PowerShell $null 是一个具有 null 或缺失值的对象。

NULL 用于表示空或未定义。变量保持为空,直到您为其分配任何值。

在这个例子中,我们将讨论PowerShell $null,检查变量是否为空,或者是否为空。

使用 PowerShell 空值检查

$null

当您在控制台上键入 $null 时,它会返回空。

检查另一个例子

$Title
$null -eq $Title

上面的命令执行 PowerShell null 检查,它返回 TRUE。

[玩转系统] PowerShell $null - 检查 null

酷提示:如何使用PowerShell Exit关键字!

使用 PowerShell $null 值

您可以将 PowerShell $null 分配给变量。

$Title = $null
Write-Output "The Title is:$Title"

此命令将 $Title 打印为空或空白。

上述命令的输出是:

PS C:\> $Title = $null                                                                           PS C:\> Write-Output "The Title is:$Title"                                                       The Title is:
PS C:\>                                                                                                   

如果您想找到变量的 $null,请在括号内使用它。

Write-Output "The Title is:[$Title]"

此命令在括号内显示 $Title 的输出和占位符。

我们在这里使用了[]。

您可以使用任何东西,例如 {} 或其他括号。

上述命令的输出是:

[玩转系统] PowerShell $null - 检查 null

使用 PowerShell $null 检查 Undefined

您可以使用 $null 来检查未定义的变量。

如果变量没有用值初始化,则它是未定义的。

$null -eq $Author

此命令检查 PowerShell 中的 $Author 是否为空。

它返回 TRUE 值,因为它尚未初始化。

酷提示:如何在 PowerShell 中替换字符串中的文本!

在数值方程中使用 $null

数值方程中的 $null 变量根据其在表达式中的使用顺序计算为 0 或 $null。

PS C:\> 10 * $null                                                                               
0
PS C:\>                                                                                                       

在上面的示例中,$null 变量的计算结果为 0,结果为 0。

PS C:\> $null * 10
PS C:\> $null -eq ($null * 10)

在此示例中,$null 变量的计算结果为 null。

它返回 TRUE。

酷提示:你知道如何在 PowerShell 中打印环境变量吗?

在函数中使用 PowerShell $null

当我们在 PowerShell 中使用该函数时,它可能会返回输出或什么也不返回。

使用 PowerShell $null 检查 PowerShell 中的函数是否返回 null。

Function ReturnFactorial(){}

$fact = ReturnsFactorial

$null -eq $fact

在上面的例子中,

PowerShell 中的 ReturnFactorial() 函数不返回任何内容,将其分配给 $fact 并检查是否为 null。

它返回一个 TRUE。

[玩转系统] PowerShell $null - 检查 null

酷提示:您知道如何在 PowerShell 中向字符串或变量添加换行符吗?

将 PowerShell $null 与数组结合使用

数组包含其中的值列表。

要访问数组或集合的值,我们使用索引。

如果我们尝试使用不包含任何值的数组或集合的索引,它将为空。

$languages  = @('C#','PowerShell','Java')
$languages[4]

在上面的示例中,$languages 包含一个大小为 3 的数组。

我们尝试访问位置 4 处的元素,该元素在数组中不可用,因此它将得到 $null 结果并抛出异常。

为了避免访问集合中的索引时出错,请检查它是否包含 $null。

PS C:\> $languages  = @('C#','PowerShell','Java')
PS C:\> $null -eq $languages[4]
TRUE

酷提示: PowerShell 字符串连接示例!

结论

上面的文章通过示例概述了 Powershell $null。

PowerShell 中的最佳实践是在使用变量之前检查变量是否为 null 或空值。

酷提示: PowerShell 在 Windows 中回显等效命令!

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯