Var is an empty string because you are explicitly passing an empty string. Empty strings are still objects, not null. Your call to Test-Function -Var $EmptyString fails to give you the output you are looking for as you are equating an empty string and null which is false in .Net. Your statement that "When Mandatory is set to $false, $Var is an empty string rather than 'DEFAULT'" is correct as you did pass something, an empty string so the assignment of the value "DEFAULT" was never called.
You could remove the Mandatory=$true in which case your "Default" value is displayed when the parameter is not passed.
function Test-Function(
[parameter( Mandatory = $false )]
[string] $Var = "DEFAULT"
){
Write-Host "Var: $Var"
}
Test-Function
This generates Var: DEFAULT as expected.
Regardless of whether the parameter is mandatory or not, if you pass an empty string the assignment to $Var = "Default" is never reached as $Var has a value of '' which while empty is actually a string.
Test-Function ''
This generates Var: Which may look like wrong but it output the empty string you told it to.
If you want to allow a default value to be assigned when the parameter is not passed use the Mandatory=$false and assign a default value as I did above. If you want to test the value that was passed and assign a default value if it was an empty string you should do that in the begin block of your function.
function Test-Function(
[parameter( Mandatory = $false )]
[string] $Var = "DEFAULT"
){
begin{if([String]::IsNullOrWhiteSpace($Var)){$Var="DEFAULT"}}
process{Write-Host "Var: $Var"}
end{}
}
Test-Function
Test-Function ''
Test-Function 'SomeValue'
This generates the following which I believe to be what you expected:
Var: DEFAULT
Var: DEFAULT
Var: SomeValue