powershell export group membership multiple job titles - powershell

I have a csv with below eachother multiple job titles so like this:
Job title 1
Job title 2
Job title 3
What I now need is to export the group memberships of the user that has that job title so for example a person with job title 1 has a couple of group memberships. I need those group memberships  in a csv. Is it possible to do this automaticly for my whole csv that it does all the job title one by one?
I have this:
Get-ADUser -Filter {title -Like "Medior Functioneel beheerder"} | Get-ADPrincipalGroupMembership | select name
How do I get it so it only does this for one match since we have multiple users with the same job title but I only need it for one user. And how do I export this to an csv preferably on one line. for each job title.

I'd approach it like this:
For each job title:
Retrieve all users with their memberOf values
Select all distinct memberships
Output a custom object with title + list of memberships
Export custom objects to CSV
$csv = #'
Title
Job title 1
Job title 2
Job title 3
'# |ConvertFrom-Csv # you'd use `Import-Csv` here instead
$result = foreach($row in $csv){
# Fetch all relevant users with their `memberOf` attribute value
$Users = Get-ADUser -Filter "title -eq '$($row.Title)'" -Properties memberOf
# Select all distinct memberOf values
$Memberships = $Users.memberOf |Sort -Unique
# Resolve the group names
$GroupNames = ($Memberships |Get-ADGroup).Name
# Output custom object
[pscustomobject]#{
Title = $row.Title
Groups = $GroupNames -join ';'
}
}
# output to CSV
$result |Export-Csv -Path .\output.csv

Related

How to look for Active Directory group name from csv in PowerShell?

If I have a .csv:
ClientCode,GroupCode
1234,ABC
1234,DEF
1235,ABC
1236,ABC
and I want to get a hashtable with ClientCode as key, and values to be all AD groups with ClientCode in it, for example:
ClientCode GroupCode
---------- ---------
1234 ClientGroup_InAD_1234, some_other_client_1234
1235 ClientGroup_InAD_1235, some_other_client_in_AD_1235
1236 ClientGroup_InAD_1236
How do I go about this?
Essentially, I have client groups in Active Directory and each client has a code which is the same as the 'ClientCode' in the csv. For example, I might have a client called 'Bob' which I have assigned a code '1234' to it. Therefore, the Group for Bob in the AD would be 'Bob_1234'. Essentially I want to be able to search for whatever groups have ClientCode in them. So i want to search for the all the AD groups that have '1234'. This would return 'Bob_1234' and whatever group in the AD also has '1234' in its name.
So far I have tried:
$clientTable = #{}
foreach($rec in $csv_data) {
$groups = #(get-adgroup -Filter "name -like '*$($rec.clientcode)_*'")
write-host "Found $($groups.count) group(s) for: $($rec.clientcode)"
$clientTable[$ClientCode] = #($groups)
}
$clientTable
but I'm not getting my desired output
You can use the loop like this. You will need to search with a * at the beginning of the name you are looking to find via the Filter.
foreach($rec in $csv) {
$clientCode = "*_$($rec.ClientCode)"
if (!($clientTable.ContainsKey($clientCode))) {
$names = Get-ADGroup -Filter 'Name -like $clientCode' | select Name
$clientTable[$clientCode] = $names -join ","
}
}
This will also check for any client IDs that have already been checked and ignore those.
If you want a hash table populated with the ClientCode value as the key name, you can do the following:
$clientTable = #{}
foreach($rec in $csv_data){
$groups = #(Get-ADGroup -Filter "Name -like '*_$($rec.ClientCode)'" | Select -Expand Name)
write-host "Found $($groups.count) group(s) for: $($rec.ClientCode)"
$clientTable[$rec.ClientCode] = $groups
}
$clientTable
Keep in mind here that each value in the hash table is an array of group names. If you want a single string with comma-delimited names, you can do $clientTable[$rec.ClientCode] = $groups -join "," instead.
You will need to de-duplicate the ClientCodes in the CSV before retrieving the groups.
Something like below should do it (assuming the ClientCode is always preceded by an underscore like in _1234 as shown in your examples)
$csv = Import-Csv -Path 'ClientGroupCodes.csv'
$clientTable = #{}
$csv | Select-Object -ExpandProperty ClientCode -Unique | ForEach-Object {
# $_ is a single clientcode in each iteration (string)
# get an array of goup names
$groups = #(Get-ADGroup -Filter "Name -like '*_$_'" | Select-Object -ExpandProperty Name)
Write-Host "Found $($groups.Count) group(s) for code : '$_'"
$clientTable[$_] = $groups -join ', '
}
$clientTable

Formatting output from PowerShell to a csv file

Trying to output two variable results from Active Directory to PowerShell and format on one line of a .csv file with each returned variable in separate cells. The input file contains the names of four AD groups. The task is to count the users in each group and return the total number of users.
The goal is to write to the .csv file formatting the output with the ad group name in one cell and the user count in the next cell to the right.
This is a simple script built by starting with reading the file and returning the results to the screen. Attempted to write to the file using Export-Csv with no success. The Add-Content has been the most successful technique.
The following code works part of the way, but the ad group name and the user count is written to the same cell in the .csv file. Earlier attempts wrote the AD group name on a line and the total # of users on the next line.
foreach($object in $groupfile){
$groupName = $object.adgroupname
$groupName = $groupName.Trim()
$users = Get-ADGroupMember -Identity $groupName
$usercount = $users.Count
$groupinfo = ($groupName + " " + $usercount)
# both of the lines below return the information to the screen on on line
Write-Host $groupname, $usercount
Write-Host $groupinfo
# this line returns the information as shown below in the First result
Add-Content -Path $filepath $groupname, $usercount
# this line writes to the file as shown below in the Second result
Add-Content -Path $filepath $groupinfo
}
First result (acceptable for a small number of groups, but a more robust solution is necessary for a larger number of groups.):
ad group name one
357
ad group name two
223
ad group name three
155
ad group name four
71
Second result (both values for the returned variable are in one cell):
ad group name one 357
ad group name two 223
ad group name three 155
ad group name four 71
The goal is to write to the .csv file formatting the output with the ad group name in one cell and the user count in the next cell to the right.
I'm assuming your variable $groupfile is the result of a Import-Csv command.
If I understand the question properly, you could do this:
# loop through the $groupfile rows and collect the results as objects
$result = $groupfile | ForEach-Object {
$groupName = $_.adgroupname.Trim()
[PSCustomObject]#{
'GroupName' = $groupName
'UserCount' = #(Get-ADGroupMember -Identity $groupName).Count
}
}
# display on screen
$result | Format-Table -AutoSize
# export to csv
$result | Export-Csv -Path $filepath -NoTypeInformation -Force
Should output a csv, something like
"GroupName","UserCount"
"ad group name one","357"
"ad group name two","223"
"ad group name three","155"
"ad group name four","71"
Note: the Get-ADGroupMember can return objects of type user, group and computer, so either name the second column ObjectCount of add a Where-Object {$_.objectClass -eq 'user'} clause to the Get-ADGroupMember function to filter only user objects
Hope that helps

Multiple rows in a grid [duplicate]

This question already has answers here:
Export hashtable to CSV with the key as the column heading
(2 answers)
Closed 4 years ago.
I'm trying to list all ad group memberships of specific users. The input would be a string of logins split with a comma 'login1,login2'.
So I go over each user and list their memberships with the username as title. Somehow it only shows the first entry. Also it shows the user groups in one row and I don't know how to change that.
Code below:
$users = $logon -split ','
$q = #()
foreach ($user in $users) {
$usernm = Get-ADUser -Filter 'samAccountName -like $user' | select Name
$useraccess = Get-ADPrincipalGroupMembership $user | Select-Object Name
$userobj = New-Object PSObject
$userobj | Add-Member Noteproperty $usernm.Name $useraccess.Name
$q += $userobj
}
Expected output would be something like:
fullnameuser1 fullnameuser2 list of users goes on...
------------- ------------- ------------------------
adgroup1 adgroup3 ...
adgroup2 adgroup4
... ...
In principle this would also mean that if i typed $q.'fullnameuser1' output would be:
fullnameuser1
-------------
adgroup1
adgroup2
...
Whenever the code is ran, it will only ever add the first user's access, also returning all groups on one row. So somehow I need to go over all the group memberships and add a row for each one.
First and foremost, PowerShell does not expand variables in single-quoted strings. Because of that Get-ADUser will never find a match unless you have a user with the literal account name $user. Also, using the -like operator without wildcards produces the same results as the -eq operator. If you're looking for an exact match use the latter. You probably also need to add nested quotes.
Get-ADUser -Filter "samAccountName -eq '${user}'"
Correction: Get-ADUser seems to resolve variables in filter strings by itself. I verified and the statement
Get-ADUser -Filter 'samAccountName -eq $user'
does indeed return the user object for $user despite the string being in single quotes.
If you want a fuzzy match it's better to use ambiguous name resolution.
Get-ADUser -LDAPFilter "(anr=${user})"
You may also want to avoid appending to an array in a loop, and adding members to custom objects after creation. Both are slow operations. Collect the loop output in a variable, and specify the object properties directly upon object creation.
$q = foreach ($user in $users) {
...
New-Object -Type PSObject -Property {
$usernm.Name = $useraccess.Name
}
}
Lastly, I'd consider using the user's name as the property name bad design. That would be okay if you were building a hashtable (which is mapping unique keys to values), but for custom objects the property names should be identical for all objects of the same variety.
New-Object -Type PSObject -Property {
Name = $usernm.Name
Group = $useraccess.Name
}
Basily query all the users and store it in $users, example:
Get-ADUser -Filter * -SearchBase "dc=domain,dc=local"
And then you can export the results as csv or a table.
To Export as CSV :
Get-ADPrincipalGroupMembership <Username> | select name, groupcategory, groupscope | export-CSV C:\data\ADUserGroups.csv`
To Format the result as Table in the console itslef :
Get-ADPrincipalGroupMembership <Username> | select name, groupcategory, groupscope | Format-Table

AD nested group membership powershell reporting

We have following naming convention for shared resources:
sg_ShareName1_RO
sg_ShareName1_RW
sg_ShareName2_RO
sg_ShareName2_RW
I would like to get report in following format in Excel/csv:
ShareName1 ShareName2 ...
User1 RW NA
User2 NA RO
I'm fighting how to output Shared names to row in csv file instead of column.
Here is come code I've already done:
$users = GetADUser - filter {name like '*'} | sort name | select name
$sharegroups = Get-AdGroup -filter {name like 'sg_*'} | sort name
$shares = Get-AdGroup -filter {name like 'sg_*'} | sort name | foreach {$_} | select #{N='Share Name'; E={$_.Name.Replace('sg_', '').Replace('_', '').Replace('RO','').Replace('RW','')}} -Unique
Tnen to avoid trips to AD each time to check group membership first i would like to store members of each group in array
$sharegroupmembers = #{}
foreach ($group in $sharegroups)
{
$sharegroupmembers[$group.name] = Get-ADGroupMember $group.name -Recursive | select name
}
After that I'm stuck on howe to make correct projection of shares to columns, users to rows and RW/RO/NA to values based on group membership
Your number of columns is going to be the maximum number of group memeberships any user has. Those are in the values of $sharegroupmembers, so:
$shargroupmembers.values |
sort count |
select -last 1
That's how many rows you'll have, and how many share membership properties you'll need to create on your objects you're going to export.

Powershell List groups and members from AD and export to CSV

I created a CSV with all the group names. The following script reads all the groups names from the "group.csv" and list the group and members.
Script:
Add-PSSnapin Quest.ActiveRoles.ADManagement
$csv = Get-Content "f:\Temp\group.csv"
$result = $csv | foreach-object {
$group=$_
get-qadgroupmember "$_" -sizelimit 0 -indirect | select-object samaccountname,#{n="GroupName";e={$group}}
}
$result | export-csv f:\temp\groupandmem.csv -notypeinformation
There are more than 1000 groups in the "group.csv" with a lot of members in each. The executing of the script stops with a memory problem and nothing is written to the groupandmem.csv because this is done at last.
I have the following questions:
Is is possible to:
- For each group in the "group.csv", list the group from CSV, search the group in the AD, display the members and write the group name and the members to the users groupandmem.csv. Do this for all the groups in the "group.csv".
-The groupandmem.csv is filled as follows:
Row 1 group,member1,members2,members3.......
Row 2 group2,member1,members2 etc.
If you start assigning things to variables then you are preventing powershell from "streaming" the users from one end of the pipe (AD) into the other end (the CSV file.) Instead, structure your pipeline like this:
Get-Content "f:\Temp\group.csv" | foreach-object {
$group = $_ # grab current group name
get-qadgroupmember $group -sizelimit 0 -indirect | `
select-object samaccountname,#{n="GroupName";e={$group}}
} | export-csv f:\temp\groupandmem.csv -notypeinformation
Now there is a true "pipeline" from start to finish: csv | foreach | get | transform | export
Before, you were backing things up by assigning everything into a variable before passing it onto the next command.
Updated: added $group to current capture group name (row)