我们有几个通过PowerShell导入到Active Directory中的几个字段,这些字段是来自数据源的空字符串,但需要在Active中设置为$null
目录。
由于这些字段中有相当多的字段,我试图创建一个将空字符串转换为$null
的函数。
问题是,如果我将变量设置回自己,它仍然是一个空字符串。如果我将它设置为一个新变量,它可以正常工作。
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 ""
这里输出
PS C:\> .\Test-Function.ps1
TestValue: False
TestValue2: True
这显然是什么我不理解有关PowerShell的函数参数类型。我可以将[string]$TestValue
更改为$TestValue
,它将起作用。
function Test-Function
{
param(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
$TestValue
)
...
}
...
输出:
PS C:\> .\Test-Function.ps1
TestValue: True
TestValue2: True
我想保留[string]
参数类型的原因是为了强制执行,它应该是一个字符串或一个空字符串。有人可以解释这里发生了什么吗?