如何在 PowerShell 中添加 header ExpandProperty?

How to add a header ExpandProperty in PowerShell?

我正在尝试构建一个脚本来帮助我使用 Kerberos 约束委派找出服务帐户。我感兴趣的两个属性是 multi-valued,因此我正在使用 -ExpandProperty 开关。不幸的是,我还没有想出一种 'clean' 方法来输出带有扩展值的 属性 名称。因为这两个扩展属性具有相似的值并且可以重叠,所以我 需要 做一些事情来显示 ServicePrincipalNames 结束和 msDS-AllowedToDelegateTo 开始的地方。下面的代码有效,但似乎应该有一种方法可以获得相同(或非常相似)的输出而不必使用 Write-Output.

$Account = "svcSomeService"

# Query AD once
$Details = Get-ADUser -Identity $Account -Properties *

# Main result set
$Details | Select-Object -Property SamAccountName, DisplayName, Enabled, PasswordNeverExpires, PasswordExpired, LockedOut, AccountNotDelegated, TrustedForDelegation, TrustedToAuthForDelegation, KerberosEncryptionType

# Expand muulti-value column ServicePrincipalNames
Write-Output "ServicePrincipalNames"
Write-Output "---------------------"
$Details | Select-Object -ExpandProperty ServicePrincipalNames    #Tried with and without Format-Table

# Expand muulti-value column msDS-AllowedToDelegateTo
Write-Output "`n"
Write-Output "msDS-AllowedToDelegateTo"
Write-Output "------------------------"
$Details | Select-Object -ExpandProperty msDS-AllowedToDelegateTo #Tried with and without Format-Table

您可以构造一个 [pscustomobject] 来容纳不同属性中的扩展值:

[pscustomobject] @{
  ServicePrincipalNames = $Details.ServicePrincipalNames
  msDS-AllowedToDelegateTo = $Details.msDS-AllowedToDelegateTo
}

注:

  • $Details.ServicePrincipalNames
    $Details | Select-Object -ExpandProperty ServicePrincipalNames 的更有效替代方案,通过 member-access enumeration 功能。

  • 至于调用方端的显示格式:由于输出对象只有两个属性,它将隐式呈现为 table(隐式 Format-Table), which doesn't provide much space for showing the individual values. Piping to Format-List helps, but additionally requires you to raise $FormatEnumerationLimit 以避免截断;[1] 以提供一个简单示例:

     $FormatEnumerationLimit=100 # !! As of v7.2.2: only effective in *global* scope
     [pscustomobject] @{ prop1 = 1..100; prop2 = 80..1 } | Format-List
    

[1] 由于至少 PowerShell 7.2.2 的不幸错误,设置此首选项变量仅在 global 范围内有效 - 请参阅GitHub issue #888.