PowerShell string default parameter value does not work as expected

前端 未结 0 376
别那么骄傲
别那么骄傲 2021-02-11 16:35
#Requires -Version 2.0

[CmdletBinding()]
Param(
  [Parameter()] [string] $MyParam = $null
)

if($MyParam -eq $null) {
  Write-Host \'works\'
} else {
  Write-Host \'doe         


        
相关标签:
回答
  • 2021-02-11 17:19

    Okay, found the answer @ https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/

    Assuming:

    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
    )
    

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

    Weird!

    0 讨论(0)
  • 消灭零回复
提交回复
热议问题