PowerShell 字符串默认参数值未按预期工作 [英] PowerShell string default parameter value does not work as expected

查看:34
本文介绍了PowerShell 字符串默认参数值未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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?这应该是两个不同的值!

Outputs "does not work" => looks like strings are converted from null to empty string implicitly? Why? And how to test if a string is empty or really $null? This should be two different values!

推荐答案

好的,找到答案@https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/

假设:

Param(
  [string] $stringParam = $null
)

并且没有指定参数(使用默认值):

And the parameter was not specified (is using default value):

# will NOT work
if ($null -eq $stringParam)
{
}

# WILL work:
if ($stringParam -eq "" -and $stringParam -eq [String]::Empty)
{
}

或者,您可以指定一个特殊的空类型:

Alternatively, you can specify a special null type:

Param(
  [string] $stringParam = [System.Management.Automation.Language.NullString]::Value
)

在这种情况下 $null -eq $stringParam 将按预期工作.

In which case the $null -eq $stringParam will work as expected.

奇怪!

这篇关于PowerShell 字符串默认参数值未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆