Skip to content

Instantly share code, notes, and snippets.

@SweetAsNZ
Created July 13, 2022 04:42
Show Gist options
  • Save SweetAsNZ/aa26f9ada9ff39401556ea405120cc95 to your computer and use it in GitHub Desktop.
Save SweetAsNZ/aa26f9ada9ff39401556ea405120cc95 to your computer and use it in GitHub Desktop.
Get Azure Group Members From AD Groups and Azure Groups
function Get-GroupMemberAz
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$Group,
[bool]$IncludeAzureGroups = $true
)
# $Group ='MFA' # Testing
$Group = "*$Group*"
Write-Host -f Green "Check AD Groups"
Get-ADGroup -Filter {Name -like $Group} | Get-ADGroupMember | Sort Name | Out-Host
if($IncludeAzureGroups -eq $true){
Write-Host -f Green "Importing AzureAD Module"
Import-Module AzureAD
# Checks if Connected To Azure AD and if not Connect.
try {
Write-Host -f Green "`r`nChecking Connection to AzureAD"
$var = Get-AzureADTenantDetail
}
catch [Microsoft.Open.Azure.AD.CommonLibrary.AadNeedAuthenticationException] {
Write-Warning "You're not connected to AzureAD. Connecting..."
# Uses whoami to stop the prompt for user name and password if alreayd authenticated
Connect-AzureAD -AccountId (Whoami /UPN)
}
# Checks if Connected and Connects In Case Company Has No Azure
If( (Get-AzureADTenantDetail).DisplayName -ne $null){
Write-Host -f Green "Connected to Azure AD"
(Get-AzureADTenantDetail).DisplayName
Write-Host -f Green "`r`nCheck Azure AD Groups"
try{
# Get Relevant Group(s)
$AzG = Get-AzureADGroup -All:$true | Where {$_.DisplayName -like "$Group"}
# If multiple groups do foreach loop
if($AzG.count -gt 1){
foreach($item in $AzG){
"`r`n"
$item.DisplayName
Get-AzureADGroupMember -ObjectId $Item.ObjectID | Sort $Item.DisplayName | Out-Host
}
}
# if a single group do this
if($AzG.count -eq 1){
"`r`n"
$AzG.DisplayName
Get-AzureADGroupMember -ObjectId $AzG.ObjectID | Sort DisplayName | Out-Host
}
}
catch{
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment