Effectively my problem comes down to this:
I can\'t have a function with a mandatory parameter and pass $null to that parameter:
Function Foo
{
P
First, add an AllowNull
attribute:
Function Foo
{
Param
(
[Parameter(Mandatory = $true)][AllowNull()][string] $Bar
)
Write-Host $Bar
}
Then, when you call the function, be aware that $null
when used for [string]
becomes an empty string, not a null reference. Therefore (since PowerShell 3 (2012)) use [NullString]::Value
like this:
Foo -Bar ([NullString]::Value)
See the documentation for System.Management.Automation.Language.NullString class.
EDIT: From the call site this appears to work, but at soon as you reach the Write-Host
cmdlet within the function, $Bar
will again have become an empty string. See comments below. We must conclude that PowerShell insists strings must be like that. Note that NullString
(which has been useful to me in other cases) in its documentation only promises to be helpful when passing null "into a .NET method".