#Requires -Version 2.0
[CmdletBinding()]
Param(
[Parameter()] [string] $MyParam = $null
)
if($MyParam -eq $null) {
Write-Host 'works'
} else {
Write-Host 'does not work'
}
输出"不起作用" =>看起来像字符串隐式地从null转换为空字符串?为什么?如何测试一个字符串是空的还是真的$ null?这应该是两个不同的值!
答案 0 :(得分:29)
好的,找到答案@ https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/
假设:
Param(
[string] $stringParam = $null
)
未指定参数(使用默认值):
# will NOT work
if ($null -eq $stringParam)
{
}
# WILL work:
if ($stringParam -eq "" -and $stringParam -eq [String]::Empty)
{
}
或者,您可以指定一个特殊的null类型:
Param(
[string] $stringParam = [System.Management.Automation.Language.NullString]::Value
)
在这种情况下,$null -eq $stringParam
将按预期工作。
怪异!
答案 1 :(得分:11)
如果您想允许AllowNull
字符串参数,则需要使用$null
属性:
[CmdletBinding()]
Param (
[Parameter()]
[AllowNull()]
[string] $MyParam
)
请注意should use $null on the left-hand side of the comparison:
if ($null -eq $MyParam)
如果你想让它以可预测的方式工作
答案 2 :(得分:2)
看到许多与[String] :: Empty的相等比较,你可以使用[String] :: IsNullOrWhiteSpace或[String] :: IsNullOrEmpty静态方法,如下所示:
param(
[string]$parameter = $null
)
# we know this is false
($null -eq $parameter)
[String]::IsNullOrWhiteSpace($parameter)
[String]::IsNullOrEmpty($parameter)
('' -eq $parameter)
("" -eq $parameter)
产生:
PS C:\...> .\foo.ps1
False
True
True
True
True
答案 3 :(得分:2)
如果您希望保留$ null值,只需 not 声明param的类型:
Param(
$stringParam
)
(在声明类型时,其他解决方案都没有。)
答案 4 :(得分:1)
因此,对于$null
类型的参数,默认值[string]
默认为空字符串,无论出于何种原因。
选项1
if ($stringParam) { ... }
选项2
if ($stringParam -eq "") { ... }
选项3
if ($stringParam -eq [String]::Empty) { ... }