在PowerShell中检查字符串是否为空
-
在PowerShell中检查字符串是否为
Not NULL或EMPTY - 在PowerShell中检查字符串是否为空的其他方法
-
使用
-eq运算符检查字符串是否为null或empty - 使用RegEx检查字符串是否为空或null
在本文中,我们将讨论在Powershell中检查给定字符串是否为null或空的方法。
在PowerShell中检查字符串是否为Not NULL或EMPTY
IsNullOrEmpty是一种常见的脚本/编程语言,用于检查给定字符串是否为空或null的字符串方法。null是一个尚未被赋值的字符串值,而empty字符串是一个具有 " "或给定的String.Empty的字符串。
在PowerShell中检查字符串是否为空的其他方法
有一种简单的方法可以实现PowerShell的IsNullOrEmpty等效函数。可以使用下面的代码段:
输入的命令中给出的字符串为null。因此,代码的输出如下所示。
示例代码1:
PS C:\Users\Test> $str1 = $null
PS C:\Users\Test> if ($str1) { 'not empty' } else { 'empty' }
输出:
empty
如果字符串是empty,输出仍然为empty。
示例代码2:
PS C:\Users\Test> $str2 = ''
PS C:\Users\Test> if ($str2) { 'not empty' } else { 'empty' }
输出:
empty
如果字符串既不是empty也不是null,输出为not empty。
示例代码3:
PS C:\Users\Test> $str3 = ' '
PS C:\Users\Test> if ($str3) { 'not empty' } else { 'empty' }
输出:
not empty
有一些命令可以比较两个字符串并检查它们是否都是empty。
PS C:\Users\Agni> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty'}
输出:
one or both empty
此外, neither empty是以上用于比较两个已声明字符串的一种可能比较方式。可以将其识别为使用IsNullOrEmpty的最清晰、最简洁的方法。
除上述方法外,还可以在PowerShell中使用IsNullOrEmpty静态方法。
使用-eq运算符检查字符串是否为null或empty
-eq运算符用于比较两个值是否相等。您可以将字符串与一个空字符串进行比较,以检查它是否为空。
代码:
$str1 = ""
if ($str1 -eq "") {
Write-Host "String is empty"
} else {
Write-Host "String is not empty"
}
输出:
String is empty
使用RegEx检查字符串是否为空或null
可以使用正则表达式来匹配字符串的模式。可以使用一个正则表达式模式来匹配空字符串或仅包含空格的字符串。
代码:
$str4 = " "
if ($str4 -match "^\s*$") {
Write-Host "String is empty"
} else {
Write-Host "String is not empty"
}
输出:
String is empty
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
