AD Queries in Powershell
14. Juni 2023
Get direct reports of user
$userSearchString = "Herwig" Get-ADUser -Filter "Name -like '*$userSearchString*'" -Properties directreports ` | Select-Object -ExpandProperty directreports ` | Get-ADUser -Properties mail ` | Sort GivenName, Surname ` | Select-Object GivenName, Surname, SamAccountName
Get manager of user
$userSearchString = "Herwig" Get-ADUser -Filter "Name -like '*$userSearchString*'" ` | ForEach{Get-ADUser $_ -properties manager} | Where-Object {$PSItem.Enabled} ` | Select-Object -ExpandProperty manager ` | Get-ADUser -Properties mail ` | Sort GivenName, Surname ` | Select-Object GivenName, Surname, SamAccountName
Get AD group members
Get-ADGroupMember "AD_group_name" -Recursive ` | ForEach{Get-ADUser $_ -properties manager} ` | Where-Object {$PSItem.Enabled} ` | Sort GivenName, Surname ` | Select-Object GivenName, Surname, SamAccountName
Find AD groups by name
Get-ADGroup -Filter 'Name -like "t2_*_rol_*"' ` | sort-object Name ` | select-object Name
Get AD group memberships by user name
$username = "Herwig" $memberOfGroups = get-aduser -Filter "Name -like '*$username*'" -Properties * ` | select givenName, Surname, SamAccountName,@{n='Groups';e={$_.memberof %{(get-adgroup $_).Name}}} ` | ConvertTo-Json > groupMemberships.json
Get AD groups wich are managed by someone
Get-ADGroup -filter {Name -like "*" } -Properties managedBy | ForEach-Object { $managedBy = $_.managedBy; Write-Host "------------------"; Write-Host $managedBy if ($managedBy -ne $null) { try { $manager = (Get-ADUser -Identity $managedBy -Properties SamAccountName); Write-Host "USER: $manager.Name"; $managerName = $manager.Name; $managerEmail = $manager.emailAddress; } catch { $manager = (Get-ADGroup -Filter {Identity -eq $managedBy} -Properties SamAccountName); Write-Host " GROUP: $manager - $managedBy"; $managerName = $managedBy; $managerEmail = $manager.emailAddress; } } else { $manager = ""; $managerName = 'N/A'; $managerEmail = 'N/A'; } Write-Output $_; } | Select-Object @{n='Group Name';e={$_.Name}}, @{n='Managed By Name';e={$managerName}} | Out-GridView