Reputation: 221
I'm looking to get the the Group Name, Managed By Name and Managed by Email in a PowerShell query similar to this.
Get-ADGroup -filter {Name -like "*Admins" }
The output would look something similar to:
Group Name | Managed By Name | Managed By Email
The issue I'm having is with joining Get-ADGroup
and Get-ADUser
. In SQL this "join" would happen on get-adgroup.managedby = get-aduser.distinguishedname
. I know that's not how it works in Powershell, just thought I'd throw out an example of what I'm trying to do.
Any help would both be welcomed and appreciated.
Upvotes: 8
Views: 56684
Reputation: 12443
I see @Mathias R. Jessen beat me to it, but here's what I had:
Get-ADGroup -filter {Name -like "*IT*" } -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object @{n='Group Name';e={$_.Name}}, @{n='Managed By Name';e={$managerName}}, @{n='Managed By Email';e={$managerEmail}}
Upvotes: 8
Reputation: 3
I would something do like this:
# Get all groups into a variable
$Group = Get-ADGroup -Filter {Name -like "*Admin*"} | Select-Object -expandProperty Name
foreach ($Groups in $Group){
# Get ManagedBy name for each group (If ManagedBy is empty group wil not be listed)
$User = Get-ADGroup $Groups -Properties * | Select-Object -ExpandProperty ManagedBy
foreach ($Users in $User){
# Get Name and EmailAddress for each User
$Name = Get-ADUser $Users | Select-Object -ExpandProperty Name
$Email = Get-ADUser $Users -Properties * | Select-Object -ExpandProperty EmailAddress
# Write output
Write-Host $Groups "," $Name "," $Email
}
}
Hope this helps.
Upvotes: 0
Reputation: 174485
You can do it like this:
$Groups = Get-ADGroup -Filter { Name -like "*Admins" } -Properties managedBy,mail
$Groups |Select-Object Name,@{Name='ManagedBy';Expression={(Get-ADUser $_.managedBy).Name}},Mail
The @{}
syntax after Select-Object
is known as a calculated property.
You could also pipe the groups to ForEach-Object
and call Get-ADUser
inside the process scriptblock:
Get-ADGroup -Filter {Name -like "*Admins"} -Properties managedBy,mail |ForEach-Object {
# Find the managedBy user
$GroupManager = Get-ADUser -Identity $_.managedBy
# Create a new custom object based on the group properties + managedby user
New-Object psobject -Property @{
Name = $_.Name
ManagedBy = $GroupManager.Name
Email = $_.mail
}
}
Upvotes: 5