Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell string default parameter value does not work as expected

#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!

like image 278
D.R. Avatar asked Apr 07 '14 07:04

D.R.


People also ask

How do I set a default parameter in PowerShell?

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.

What is param () in PowerShell?

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.

How do you make a parameter mandatory in PowerShell?

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.


Video Answer


2 Answers

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!

like image 59
D.R. Avatar answered Oct 09 '22 22:10

D.R.


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

like image 44
oɔɯǝɹ Avatar answered Oct 09 '22 23:10

oɔɯǝɹ