We have a few imports via PowerShell in to Active Directory that have a couple fields that come across as an empty string from the datasource, but need to be set as $null within Active Directory.
Since there are quite a few of these fields, I attempted to create a function that will convert an empty string to $null.
The trouble is that if I set the variable back to itself, it remains an empty string. If I set it as a new variable, it works fine.
function Get-ValueOrNull
{
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[string]$Value
)
if ([string]::IsNullOrEmpty($Value))
{
return $null
}
return [string]$Value
}
function Test-Function
{
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[string]$TestValue
)
$TestValue = Get-ValueOrNull -Value $TestValue
$TestValue2 = Get-ValueOrNull -Value $TestValue
Write-Host "TestValue: $($TestValue -eq $null)"
Write-Host "TestValue2: $($TestValue2 -eq $null)"
}
Test-Function -TestValue ""
Here the output is
PS C:\> .\Test-Function.ps1
TestValue: False
TestValue2: True
This is clearly something I'm not understanding about Types in PowerShell function parameters. I can change the [string]$TestValue to $TestValue, and it will work.
function Test-Function
{
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
$TestValue
)
...
}
...
Output:
PS C:\> .\Test-Function.ps1
TestValue: True
TestValue2: True
The reason I'd like to preserve the [string] parameter type is to enforce that it should be a string or an empty string. Can someone explain what is going on here?