Using PowerShell script If Else or Try catch, how can I modify the below script, if the Group member type = Computer, then use Get-MGDevice to display the display name.
$GROUP_LIST = Get-MgGroup -Filter "groupTypes/any(c:c eq 'DynamicMembership')" -All:$true | Select-Object Id, DisplayName, Description, GroupTypes
$users = $GROUP_LIST | ForEach-Object {
$Group = $_
Write-Host "Processing $($Group.DisplayName)" -ForegroundColor Cyan
$members = Get-MgGroupMember -GroupId $Group.Id -Property "id,displayName,userPrincipalName,companyName"
Write-Host "`t [$($Group.DisplayName)] Member count [$($members.Count)]" -ForegroundColor Yellow
$members | ForEach-Object {
$member = $_
Try {
$user = Get-MgUser -UserId $member.Id -Property Id, DisplayName, Mail, UserPrincipalName, CompanyName |
Select-Object Id, DisplayName, Mail, UserPrincipalName, CompanyName
[PSCustomObject]@{
Group = $Group.DisplayName
Name = $user.DisplayName
USERPRINCIPALNAME = $user.Mail
CompanyName = $user.CompanyName
}
} Catch {
Try {
$device = Get-MgDevice -DeviceId $member.Id -Property Id, DisplayName |
Select-Object Id, DisplayName
[PSCustomObject]@{
Group = $Group.DisplayName
Name = $device.DisplayName
USERPRINCIPALNAME = "N/A"
CompanyName = "N/A"
}
} Catch {
Write-Host "Unable to find user or device for member ID $($member.Id)" -ForegroundColor Red
[PSCustomObject]@{
Group = $Group.DisplayName
Name = "Unknown"
USERPRINCIPALNAME = "N/A"
CompanyName = "N/A"
}
}
}
}
}
$users | Out-GridView
The PowerShell script above works fine for the Get-MgUser part, however, the Get-MgDevice is not returning any value or empty.
Thank you for the assistance.