Home > Net >  How to add a header ExpandProperty in PowerShell?
How to add a header ExpandProperty in PowerShell?

Time:03-24

I am trying to build a script to help me figure out service accounts using Kerberos Constrained Delegation. Two of the properties that I am interested in are multi-valued, so I am using the -ExpandProperty switch. Unfortunately, I haven't figured out a 'clean' way to output the property name with the expanded values. Because the two expanded properties have similar values and can overlap, I need to do something to show where ServicePrincipalNames ends and msDS-AllowedToDelegateTo begins. The code below works, but it seems like there should be a way of getting the same (or very similar) output without having to use 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

CodePudding user response:

You can construct a [pscustomobject] that houses the expanded values in distinct properties:

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

Note:

  • $Details.ServicePrincipalNames is a more efficient alternative to
    $Details | Select-Object -ExpandProperty ServicePrincipalNames, via the member-access enumeration feature.

  • As for display formatting on the caller's side: Since the output object has only two properties, it will implicitly render as a table (implicit 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 to avoid truncation;[1] to provide a simple example:

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

[1] Due to an unfortunate bug up to at least PowerShell 7.2.2, setting this preference variable is only effective in the global scope - see GitHub issue #888.

  • Related