如何在PowerShell中添加标头ExpandProperty?



我正在尝试构建一个脚本来帮助我使用 Kerberos 约束委派找出服务帐户。我感兴趣的两个属性是多值的,所以我使用 -ExpandProperty 开关。不幸的是,我还没有找到一种"干净"的方式来输出带有扩展值的属性名称。由于两个展开的属性具有相似的值并且可能重叠,因此我需要执行一些操作来显示 ServicePrincipalNames 结束的位置和 msDS-AllowedToDelegateTo 开始的位置。下面的代码有效,但似乎应该有一种方法可以在不必使用写入输出的情况下获得相同(或非常相似)的输出。

$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更有效
    的替代方案,通过成员访问枚举功能。

  • 至于调用方端的显示格式:由于输出对象只有两个属性,它将隐式呈现为(隐式Format-Table),这没有提供太多空间来显示单个值。管道到Format-List有帮助,但还需要您提高$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 之前有一个不幸的错误,设置此首选项变量仅在全局范围内有效 - 请参阅 GitHub 问题 #888。

最新更新