Skip to content

Instantly share code, notes, and snippets.

@WimObiwan
Last active September 17, 2024 08:46
Show Gist options
  • Save WimObiwan/44a893ef23d1b7bfe88b6cd7bc670ad2 to your computer and use it in GitHub Desktop.
Save WimObiwan/44a893ef23d1b7bfe88b6cd7bc670ad2 to your computer and use it in GitHub Desktop.
Select-GraphObject.ps1 to flatten objects returned by Microsoft Graph, Azure, ... Powershell cmdlets
#usage:
# Get-MgGroupMember -GroupId <someid> | `
# Select-GraphObject displayname, userprincipalname, mail, officelocation
#based on https://stackoverflow.com/questions/72384632/possible-to-pull-info-from-additionalproperties-dictionary-with-microsoft-graph
#with some changes to make it work
function Select-GraphObject {
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory, ValueFromPipeline, DontShow)]
[object] $InputObject,
[Parameter(Position = 0)]
[SupportsWildcards()]
[string[]] $Properties = '*'
)
begin {
$firstObject = $true
$toSelect = [Collections.Generic.List[object]]::new()
}
process {
if($firstObject) {
foreach($property in $InputObject.PSObject.Properties) {
foreach($item in $Properties) {
if($property.Value -is [Collections.IDictionary]) {
foreach($key in $property.Value.PSBase.Keys) {
if($key -like $item -and $key -notin $toSelect.Name) {
$toSelect.Add(@{
Property = $property.Name
Key = $key
})
}
}
continue
}
if($property.Name -like $item -and $property.Name -notin $toSelect) {
Write-Warning "$($property.Name)"
$toSelect.Add($property.Name)
}
}
}
$firstObject = $false
}
$out = [ordered]@{}
foreach($item in $toSelect) {
if($item -isnot [hashtable]) {
$out[$item] = $InputObject.$item
continue
}
# $enum = $item.GetEnumerator()
# if($enum.MoveNext()) {
# $enum.Current.Value
# $out[$enum.Current.Key] = $InputObject | & $enum.Current.Value
# }
$out[$item.Key] = $InputObject.$($item.Property)[$item.Key]
}
[pscustomobject] $out
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment