gpt4 book ai didi

powershell - 为什么当我在 PowerShell 中通过引用传递此属性时未更新它

转载 作者:行者123 更新时间:2023-12-03 16:41:07 25 4
gpt4 key购买 nike

有人可以解释为什么在下面的示例中函数退出后属性的更新没有被持久化

function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject

# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"

return $Config
}

function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.Value
Write-host "Are the objects equal? " $obj.Value.Equals($config.MyProperty)

$obj.Value = "New Value"
Write-Host "Inside function After Updating : " $obj.Value

}



$config = CreateConfigObject

Write-Host "Before calling function : " $config.MyProperty

MyFunction ([ref]$config.MyProperty)

Write-Host "After calling function : " $config.MyProperty

最佳答案

想了想,但我找到了答案。 [ref] 将对象而不是值传递给函数。因此,您需要做的是将 $config 传递给该函数,然后引用它的值,以及该值的 .MyProperty 属性。看看这段稍微改动过的代码,看看我的观点:

function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject

# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"

return $Config
}

function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.value.MyProperty
Write-host "Are the objects equal? " $obj.value.MyProperty.Equals($config.MyProperty)

$obj.value.MyProperty = "New Value"
Write-Host "Inside function After Updating : " $obj.value.MyProperty

}



$config = CreateConfigObject

Write-Host "Before calling function : " $config.MyProperty

MyFunction ([ref]$config)

Write-Host "After calling function : " $config.MyProperty

这将输出预期的结果:

Before calling function :  Original Value
Inside function Before Updating : Original Value
Are the objects equal? True
Inside function After Updating : New Value
After calling function : New Value

关于powershell - 为什么当我在 PowerShell 中通过引用传递此属性时未更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26182004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com