将空字符串转换为$null再赋值给同一变量

3

我们通过PowerShell将一些数据导入到Active Directory中,其中有几个字段从数据源传递过来时为空字符串,但需要在Active Directory中设置为$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]参数类型的原因是为了强制其只能是字符串或空字符串。有人能解释一下这是怎么回事吗?

1个回答

5
一旦你将变量作为被分配的值的替代物而不是该值本身进行了转换,你就在严格地类型化该变量。
使用 [int] 更容易理解,因为基本上任何东西都可以成功地转换为 [string]
$v = [int]'5'
$v.GetType()  # int

$v = 'hello'
$v.GetType()  # string

[int]$v = '5'
$v.GetType()  # int

$v = 'hello'
# Exception:
# Cannot convert value "hello" to type "System.Int32". Error: "Input string was not in a correct format."

当您输入参数时,包含参数的变量也是如此;您可以重新分配它,但右侧必须可分配/可转换为左侧类型。

$null 转换为 [string] 是一个空字符串:

([string]$null) -eq ([string]::Empty)  # True

如果在函数中使用不同的中间变量,您仍然可以强制类型转换参数,就像您展示的那样使用$TestValue2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接