#Requires -Version 2.0 [CmdletBinding()] Param( [Parameter()] [string] $MyParam = $null ) if($MyParam -eq $null) { Write-Host 'works' } else { Write-Host 'does not work' }
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!
You can use a script block to specify different default values for a parameter under different conditions. PowerShell evaluates the script block and uses the result as the default parameter value. The Format-Table:AutoSize key sets that switch parameter to a default value of True.
The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.
To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out. Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.
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!
You will need to use the AllowNull
attribute if you want to allow $null
for string parameters:
[CmdletBinding()] Param ( [Parameter()] [AllowNull()] [string] $MyParam )
And note that you should use $null on the left-hand side of the comparison:
if ($null -eq $MyParam)
if you want it to work predictably
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With