【发布时间】:2014-11-13 22:26:22
【问题描述】:
我在 XP 上运行 Powershell V2: 这是一个较大脚本的一部分,我注意到我能够使用引用对象来更新“主”对象的方式存在一些异常。这开始是为了避免每次都输入复杂的属性名称 - 我可以轻松扩展为全名,但现在这种行为的原因严重困扰我。
[CmdletBinding()]
Param()
Function Breakhere {Write-Verbose " "}
Set-PSBreakpoint -Command Breakhere
$Data = @"
UserID
MyUser1
MyUser2
User3
"@
$Data = $Data|ConvertFrom-Csv
$Domains = "DomainA","DomainB"
$Props = "ParentContainer","AccountIsDisabled","employeeNumber"
$Connection = New-Object HashTable
ForEach ($Domain in $Domains)
{
Write-Verbose "Current Domain: $Domain"
# Add necessary headers to main data
$text1 = "$($Domain)_ADObject"
$text2 = "$($Domain)_Confidence"
$Data = $Data |Select *,$text1
$Data = $Data |Select *,$text2
#Bind to each domain and save the connection contexts into a hashtable
Write-Verbose "Binding to $Domain"
$Connection.Add($Domain,(Connect-QADService -service $Domain))
}
ForEach ($User in $Data)
{
ForEach ($Domain in $Domains)
{
$User."$($Domain)_ADObject" = Get-QADUser -Connection $Connection[$Domain] -SamAccountName $User.UserID -DontUseDefaultIncludedProperties -IncludedProperties $Props|Select $Props
# Referencing the confidence parameter does not seem to work.
$CF = [ref]$User."$($Domain)_Confidence"
# Weirdly, this one does work.
$AD = [ref]$User."$($Domain)_ADObject"
If ($AD.Value)
{
$CF.Value = 1
Breakhere # Break here and allow for opportunity to inspect $user and $CF objects
If ($AD.Value.AccountIsDisabled)
{
Write-Verbose "$Domain\$($User.UserID): Account Disabled"
$CF.Value *= 0.8
}
}
Else
{
Write-Verbose "$Domain\$($User.UserID): No AD Object found"
$CF.Value = 0
}
}
} #End ForEach $UserID
在断点处,如果我查询 $User,我会收到类似于以下内容的信息:
UserID : MyUser1
DomainA_ADObject : @{ParentContainer=DomainA/Users; AccountIsDisabled=False; employeeNumber=123456}
DomainA_Confidence :
DomainB_ADObject :
DomainB_Confidence :
一切都好。如果我愿意,我什至可以使用 $AD ref 对象并更新 DomainA_ADobject:
$AD.Value.employeeNumber = 9999
$User
UserID : MyUser1
DomainA_ADObject : @{ParentContainer=DomainA/Users; AccountIsDisabled=False; employeeNumber=9999}
DomainA_Confidence :
DomainB_ADObject :
DomainB_Confidence :
但是,用 $CF ref 试试这个,同样的事情不会发生
$CF.Value = 2
$CF
Value
-----
2
$User
UserID : MyUser1
DomainA_ADObject : @{ParentContainer=DomainA/Users; AccountIsDisabled=False; employeeNumber=9999}
DomainA_Confidence : *<====== Expecting this to update!*
DomainB_ADObject :
DomainB_Confidence :
为什么不一样?有什么方法可以查询 [ref] 对象并查看它指向的内容吗?我不明白为什么其中一个有效而另一个无效。它们似乎都以相同的方式设置。在 ISE 和控制台中尝试过此操作,两者的行为相同。
【问题讨论】:
-
我遇到了类似的情况,似乎找不到解释
-
[ref]不应该在这里工作。它用于调用带有ref参数的方法,而不是用于引用属性。
标签: powershell pass-by-reference