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.
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}}
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
}
}
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.
Related
I can get the user accounts in the group with the following script. But I want to get both computer object and user object in some groups. how can I do it?
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter "Name -like 'TST*'"
ForEach ($Group in $Groups) {
Get-ADGroupMember -Identity $group |
Get-ADUser -Properties samaccountname,mail,AccountExpires,manager,employeeid,employeetype |
Select-Object samaccountname,mail,employeeid,employeetype,#{l="expiration_date";e={ accountExpiresToString($_.AccountExpires)}},#{n=”Manager Name”;e={(Get-ADuser -identity $_.Manager -properties displayname).DisplayName}} |
Export-CSV -Path "C:tmp\$($group.Name).csv" -NoTypeInformation
}
Just test for the objectclass and deal with accordingly. Use a custom object to construct the output.
Import-Module ActiveDirectory
$groups = Get-ADGroup -Filter "Name -like 'TST*'"
$groups | ForEach-Object {
$Results = Get-ADGroupMember -Identity $_ | ForEach-Object {
#
# For each objectclass you must output the same properties else
# the custom PS object will not construct across object types
# I find this the best way to make it obvious what your code is doing:
#
If ($_.objectclass -eq 'user') {
$ObjDetails = Get-ADUser -Identity $_ -Properties mail,AccountExpires,manager,employeeid,employeetype
$Mail = $ObjDetails.mail
$EmployeeID = $ObjDetails.employeeid
$EmployeeType = $ObjDetails.employeetype
# Unless you're SURE all these fields are populated correctly use Try...Catch or test for the field before assigning
Try {
$ManagerName = (Get-ADuser -identity $ObjDetails.Manager -properties displayname -ErrorAction Stop).DisplayName
}
Catch {
$ManagerName = 'Not found'
}
# Not in a User object, but you must define empty fields
$DNSHostName = ''
}
If ($_.objectclass -eq 'computer') {
$ObjDetails = Get-ADComputer -Identity $_ -Properties DNSHostName
# These fields are not in a Computer object but you must define them
$Mail = ''
$EmployeeID = ''
$EmployeeType = ''
$ManagerName = ''
# This field unique to computer object
$DNSHostName = $ObjDetails.DNSHostName
}
[pscustomobject]#{
SamAccountName = $ObjDetails.SamAccountName
Mail = $Mail
EmployeeID = $EmployeeID
EmployeeType = $EmployeeType
ManagerName = $ManagerName
DNSHostName = $DNSHostName
}
}
# You can then display/export results object
$Results # | Export-CSV -Path "C:\tmp\$($group.Name).csv" -NoTypeInformation
}
I created a script to pull some info from AD, the problem I'm having is the Secondary SMTP address field has more then one line. I'd like to show each secondary SMTP in a new line. My Script output looks like {smtp:joe.rodriguez#con...
$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'
$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase |select -expand samaccountname
Foreach ($user in $users){
$Secondary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "False"} |select -ExpandProperty $_.Smtpaddress
New-Object -TypeName PSCustomObject -Property #{
Name = Get-ADUser -Identity $user -Properties DisplayName |select -ExpandProperty DisplayName
"Login ID" = Get-ADUser -Identity $user -Properties SamAccountName |select -ExpandProperty SamAccountName
Primary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress
Secondary = $Secondary
}
}
Personally I'd make an array, pull your user list, and then iterate through the secondary SMTP addresses for each user adding your custom object to the array for each entry.
$Userlist = #()
$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'
$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase -Properties DisplayName
Foreach ($user in $users){
$Recip = get-recipient -Identity $user.samaccountname -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP"}
$Recip|? {$_.IsPrimaryAddress -like "False"} |select -ExpandProperty Smtpaddress |%{
$UserList += New-Object -TypeName PSCustomObject -Property #{
Name = $User.DisplayName
"Login ID" = $User.SamAccountName
Primary = $Recip|? {$_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress
Secondary = $_
}
}
}
This script (based off your script above) also reduces the number of server queries by 3 per user I think, so it should run a ton faster.
I have a list of users full name that I'd like to get their SAMaccount name but when I run my code I get no results. Anyone have any ideas?
$users = Get-Content C:\users\admin\Desktop\move.txt
foreach ($user in $users){
Get-ADUser -Filter {Name -eq "$user"} |Select-Object name, samaccountname
}
It could be that $user is null inside the script block. Try to use double quotes instead of braces and put the variable in single quotes to make the valid query (name contain spaces):
Get-ADUser -Filter "Name -eq '$user'" | Select-Object name, samaccountname
Here is a powershell script that should work for you. You'll want to go to the link to read the fine details, http://wbarena.com/2015/01/powershell-find-ad-user-full-name.html.
Import-Module ActiveDirectory
$aResults = #()
$List = Get-Content “.\List.txt”
ForEach($Item in $List){
$Item = $Item.Trim()
$User = Get-ADUser -Filter{displayName -like $Item -and SamAccountName -notlike “a-*” -and Enabled -eq $True} -Properties SamAccountName, GivenName, Surname, telephoneNumber, mail
$hItemDetails = New-Object -TypeName psobject -Property #{
FullName = $Item
UserName = $User.SamAccountName
Email = $User.mail
Tel = $User.telephoneNumber
}
#Add data to array
$aResults += $hItemDetails
}
$aResults | Export-CSV “.\Results.csv”
Use first and last name separately.
foreach ($user in $users){
$SplitName = -split $user
Get-ADUser -Filter {(GivenName -eq $SplitName[0]) -and (Surname -eq $splitName[1])} |Select-Object name, samaccountname
}
I have a requirement to generate a CSV report to get group members. However, I there are many child domains which contains groups starting with ADM.
I need report in the following format:
GroupName User Company LasLogon CN
ADM_AM UserOne CP1
I've found one script on internet:
Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"' |
ForEach-Object{
$hash=#{GroupName=$_.Name;Member=''}
$_ | Get-ADGroupMember -ea 0 -recurs |
ForEach-Object{
$hash.Member=$_.Name
New-Object psObject -Property $hash
}
} |
sort groupname,member
This script only gives me GroupName and UserName but not other information.
How can I generate this report?
I'm not sure what "ADM_AM, UserOne, CP1" is, but i got this much for you. I'm still new to powershell so forgive me if this is a lot of code =)
$array = #()
Foreach ($group in (Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"'))
{
$hash=#{Username ='';GroupName=$group.Name;Company='';LastLogon='';CN=''}
$members = $hash.GroupName | Get-ADGroupMember -Recursive -ErrorAction SilentlyContinue
Foreach($member in $members)
{
$properties = $member.SamAccountName | Get-ADUser -Properties SamAccountName, Company, lastLogon, CN
$hash.Username = $properties.SamAccountName
$hash.Company = $properties.Company
$hash.LastLogon = $properties.lastLogon
$hash.CN = $properties.CN
$obj = New-Object psObject -Property $hash
$array += $obj
}
}
$array | Export-Csv C:\ -NoTypeInformation
Here is what I would do, Im sure you can shorten it. You shoud specify a searchbase. Once you have the members samaccountname, you can use Get-ADUser to get whatever fields you want.
$GrpArr = #()
$Groups = get-adgroup -filter {name -like "adm*"} -searchbase "ou=Groups,dc=all,dc=ca" | select samaccountname
foreach ($group in $groups)
{
$GrpArr += $group
$members = get-adgroupmember $group | select samaccountName
foreach ($member in $members)
{
$memprops = get-aduser $member -properties company
$comp = $memprops.company
$grpArr += "$member,$comp"
}
}
$grpArr | export-csv c:\temp\Groups.csv -NoTypeInformation
edited from original question because the real problem was something unrelated to the question
I got a list of trustees from NTFS permissions and now I want to expand the groups to show membership. If I have a SAM name like MyDomain\name, there's no indication of whether that is a group or not. The Get-ADobject command has an ObjectClass property which will indicate group or user if this is an Active Directory domain object. One can use:
Get-ADObject -filter 'SamAccountName -eq "My Users"' or
$sam = "My Users"
Get-ADObject -filter 'SamAccountName -eq $sam'
Thanks to JPBlanc who had an alternate form of writing that with a script block and some other suggestions.
And thanks, user2142466. That looks like a good suggestion for my original script.
You can use a variavle using :
$sam = "My Users"
Get-ADObject -Filter {(SamAccountName -eq $sam)}
But I agree that using vars in -Filter sometimes results in strange behaviours with vars (see this question), so I prefer to use -LDAPFilter.
Get-ADObject -LDAPFilter "(SamAccountName =$user)"
Be careful the -LDAPFilter use polish notation for the filter, it's a bit disconcerting at the begining, but here, it's the natural way of filtering using the underlaying protocol LDAP.
You can get more information about this syntax in Search Filter Syntax, you can also get corresponding filters in About_ActiveDirectory_Filter.
I am guessing you are getting an array of trustees. (i.e User,Group,user,user,Group). So if you get a group then you want to pull the members from it too?
So I would look to see if it is a group, like how you are doing first and then pulling those members out of it. Add it to an another array which will contain every single user for your NTFS permissions.
$arraytrustees
#Create a blank Array
$NTFSUsers =#()
for each ($object in $arraytrustees){
$ObjectClass = (Get-ADObject -filter {SamAccountName -eq $object}).ObjectClass
If ($ObjectClass -eq "group"){
$AdGroupUsers = (Get-ADGroupMember -identity $object).SamAccountName
$NTFSUsers = $NTFSUsers + $AdGroupUsers
}else{
$NTFSUsers = $NTFSUsers + $ojbect
}
}
I was asked to list all members of the groups, along with their ID, Name, and Description as well, so I added a couple of lines.
cls
$Users = #()
$Groups = #()
$list = Get-Content z:\pcm2.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
If ($ObjectClass -eq "User")
{
$U = Get-ADUser -Properties * -Identity $o
$User = "" | Select FullUserName, LoginID, Description
$User.FullUserName = $U.DisplayName
$User.LoginID = $U.SamAccountName
$User.Description = $U.description
$Users += $User
}
Else
{
If ($ObjectClass -eq "Group")
{
$G = Get-ADGroup -Properties * -Identity $o
$GM = Get-ADGroupMember -Identity $G.name -Recursive | Get-ADUser -Properties *
Foreach ($gmember in $GM)
{
$Group = "" | Select GroupName, GroupDescription, GroupMemberName, GroupMemberLoginID, GroupMemberDesc
$Group.GroupName = $G.Name
$Group.GroupDescription = $G.Description
$Group.GroupMemberName = $gmember.Name
$Group.GroupMemberLoginID = $gmember.SamAccountName
$Group.GroupMemberDesc = $gmember.Description
$Groups += $Group
}
}
}
}
$Users | Export-Csv z:\PCMUsers.csv -NoTypeInformation
$Groups | Export-Csv z:\PCMGroups.csv -NoTypeInformation
I received a list and was asked to determine whether the objects were users or group, and I came up with this. It worked!
cls
$Users = #()
$Groups = #()
$list = Get-Content z:\pcm.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
If ($ObjectClass -eq "User")
{
$U = Get-ADUser -Properties * -Identity $o
$User = "" | Select FullUserName, LoginID, Description
$User.FullUserName = $U.DisplayName
$User.LoginID = $U.SamAccountName
$User.Description = $U.description
$Users += $User
}
Else
{
If ($ObjectClass -eq "Group")
{
$G = Get-ADGroup -Properties * -Identity $o
$Group = "" | Select GroupName, Description
$Group.GroupName = $G.Name
$Group.Description = $G.Description
$Groups += $Group
}
}
}
$Users | Export-Csv z:\Users.csv -NoTypeInformation
$Groups | Export-Csv z:\Groups.csv -NoTypeInformation