Is there a better way to get users' information and their manager for a specific MemberOf Group in Graph API in Powershell? I have written below, it works but doesn't seem to be the best way to do this. I am new to this so please take it easy on me!
Ideally, I would like ALL fields from the Get-MgUser with the user's Manager and the specific MgUserMemberOf group I am searching for at the end of the CSV export, but not sure if it is possible.
if (Get-InstalledModule Microsoft.Graph) {
# Connect to MS Graph $appid = 'BLAH' $tenantid = 'BLAH' $secret = 'BLAH'
$body = @{
Grant_Type = 'client_credentials'
Scope = 'https://graph.microsoft.com/.default'
Client_Id = $appid
Client_Secret = $secret
}
$connection = Invoke-RestMethod `
-Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token `
-Method POST `
-Body $body $token = $connection.access_token Connect-MgGraph -AccessToken $token
### Comment out below to use the production version of Azure AD
Select-MgProfile -Name 'beta'
$users = Get-MgUser -Filter "startsWith(DisplayName, 'Joe Bloggs')"
foreach($Id in $users) {
$MemberOf = Get-MgUserMemberOf -UserId $CurrentID | Where-Object { $_.AdditionalProperties['displayName'] -like '*VIP*' } | Select-Object id, @{E = { $_.additionalProperties['displayName'] } }
$UserManager = Get-MgUserManager -UserId $CurrentID | Select-Object id, @{E = { $_.additionalProperties['displayName'] } }
$Result = "$($users.Id) , ""$($users.DisplayName)"", ""$($UserManager.'$_.additionalProperties[''displayName'']')"", ""$($MemberOf.'$_.additionalProperties[''displayName'']')"""
Write-Host $Result
Add-Content 'C:\Temp\Result.csv' $Result
}
}
Current Export
00000000-56fa-4638-9ff6-1dc85d3c9735 , "DISPLAY NAME", "MANAGER", "Member Of GROUP"
Your code is very confusing but I think what you're looking for is something similar to this. For sure you should be building your CSV manually, you can create objects and the pass them through the pipeline to Export-Csv
to parse them for you. In both cases, you can use -ExpandProperty
instead of calling Get-MgUserManager
and Get-MgUserMemberOf
separately.
if (Get-Module Microsoft.Graph -ListAvailable) {
$params = @{
Uri = "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token"
Method = 'POST'
Body = @{
Grant_Type = 'client_credentials'
Scope = 'https://graph.microsoft.com/.default'
Client_Id = $appid
Client_Secret = $secret
}
}
$connection = Invoke-RestMethod @params
Connect-MgGraph -AccessToken $connection.access_token
Select-MgProfile -Name 'beta'
$getMgUserSplat = @{
Filter = "startsWith(DisplayName, 'Joe Bloggs')"
ExpandProperty = 'manager', 'memberOf'
}
Get-MgUser @getMgUserSplat | ForEach-Object {
[pscustomobject]@{
Id = $_.Id
DisplayName = $_.DisplayName
Manager = $_.Manager.AdditionalProperties.displayName
MemberOf = $_.memberOf.AdditionalProperties.displayName -like '*VIP*'
}
} | Export-Csv 'C:\Temp\Result.csv' -NoTypeInformation
}