A 计算属性的故障排除技术:
脚本块存储在Expression
定义一个哈希表的条目计算属性 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Calculated_Properties:
-
运行在child范围相对于调用者的范围。
-
更重要的是,它静静地忽略任何错误发生的情况。
然而,这样的错误are记录在自动的$Error多变的 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#error,因此要诊断您的问题,您可以执行以下操作:
$Error.Clear()
Search-ADAccount -LockedOut -UsersOnly |
Select-Object Name, SamAccountName, @{Name="OU";Expression={(Get-ADOrganizationalUnit -Identity $_.DistinguishedName).CanonicalName}}
$Error # Output the errors that occurred inside the calculated property's script block.
针对您的具体问题的解决方案:
As Santiago Squarzon 的有用答案 https://stackoverflow.com/a/69989948/45375解释说,你需要提取OU的专有名称 (DN) 来自user's并将前者传递给Get-ADOrganizationalUnit -Identity
.
While $_.DistinguishedName.Split(',',2)[1]
,这会删除第一个,
-将令牌与用户的 DN 分开通常工作,它可能会因 DN 使用而失败escaped ,
字符。 (\,
) 将被视为值的一部分;例如。:
# !! Simple splitting by the first "," is NOT enough here:
PS> 'CN=Martin Luther King\, Jr.,OU=Ministry,DC=example,DC=org'.Split(',',2)[1]
Jr.,OU=Ministry,DC=example,DC=org # !! WRONG - split at the *escaped* ","
还要处理这些边缘情况,即to robustly从用户的 OU 中提取 DN, 一个复杂的regex https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Regular_Expressions需要结合-replace操作员 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#replacement-operator:
# OK: The regex correctly recognizes the escaped \, as such.
PS> 'CN=Martin Luther King\, Jr.,OU=Ministry,DC=example,DC=org' -replace '^.+?((?<=[^\\])(?:\\\\)*),'
OU=Ministry,DC=example,DC=org # OK
把它们放在一起:
Search-ADAccount -LockedOut -UsersOnly |
Select-Object Name,
SamAccountName,
@{
Name = 'OU'
Expression = {
(Get-ADOrganizationalUnit -Identity ($_.DistinguishedName -replace '^.+?((?<=[^\\])(?:\\\\)*),')).CanonicalName
}
}