Powershell get-adgroupmembership text file - powershell

Currently i have:
import-module activedirectory
$path = get-content "E:\test.txt" | Out-String
$path | ForEach-Object { Get-ADGroupMember $_ | Select-Object name }
This gets the names (lastname_firstInitial) of the users within the group specified in the text file.
The text file looks somthing like:
groupname1
groupname2
...
groupname50
is there a way to output the full name of the user "displayname" property, get-adgroupmember does not support the -property displayname or firstname & last name - i also need the names to appear next to the correct group they were pulled from.
Currently i can only retrieve the "logon names" but have no idea what group they were pulled from.
Thank you.
Phil

When issuing this command you get a list of all members, each containing a unique ID in the AD. You could use this to fetch the actual ADUserObject and work your way from there.
$Filename = "C:\temp\groups.txt"
#ForEach ( $GroupName in [System.IO.File]::ReadLines($Filename) ) {
ForEach ( $GroupName in (Get-Content $Filename) ) {
$UserIDs = (Get-ADGroupMember $GroupName).ObjectGUID
ForEach ( $UserID in $UserIDs ) {
$ADUser = Get-ADUser $UserID -Properties DisplayName
Write-Output "$GroupName : $($ADUser.DisplayName)"
}
}

Related

query powershell to pull users from a list and return all of their groups to a file

I have a list of 800+ users that I would like to get a list of each user's AD groups and then output the user's name(samAccountName in my file) and their groups to a file.
I have tried the following code, but it does not put the Account name, and is not parsing all of the entries in the file - I have 9 entries, I get a text file with 5 groupings of groups.
The code I am using:
$users = Get-Content C:\scripts\vendors.txt
ForEach ($User in $users) {
Get-ADPrincipalGroupMembership $user | select $user.samaccountname |Select Name | Sort Name | ft #{L='Current Groups';E={$PSItem.Name}} -AutoSize | Out-File -append c:\scripts\vendorlog.txt
}
You already know how to get a user's membership via Get-ADPrincipalGroupMembership, seems like you only need help with enumerating each group and then merging that output with the user being processed, for that you can use PSCustomObject to instantiate and output new objects, then that output can be captured and exported to CSV with Export-Csv.
Get-Content C:\scripts\vendors.txt | ForEach-Object {
try {
foreach($group in Get-ADPrincipalGroupMembership $_) {
[pscustomobject]#{
UserName = $_
MemberOf = $group.Name
}
}
}
catch {
Write-Warning $_
}
} | Export-Csv path/to/myExport.csv -NoTypeInformation

Powershell script to check if users in an csv file are existing in AD and to create 2 output lists

I am not really good at scripting, but I tried for a couple of hours to create a script which will look through a UserList.csv and will output: 1. existingAccounts.txt 2.NotExistingAccounts.txt. It works but I would like for 1. existingAccounts.txt to include also Properties like: Description,Email of the accounts.
the script:
Import-Module ActiveDirectory
$UserList = get-content E:\Users\JohnDoe\Desktop\UserList.csv
Foreach ($Item in $UserList) {
$user = $null
$user = Get-aduser -filter {samAccountName -eq $Item}
if ($user)
{
$user | Out-File E:\Users\JohnDoe\Desktop\existingAccounts.txt -encoding default -append
}
else
{
"$item does not exist" | Out-File E:\Users\JohnDoe\Desktop\NotExistingAccounts.txt -encoding default -append
}
}
existingAccounts.txt produces:
DistinguishedName : CN=John DOE,OU=BOF
Management,OU=Privileged,OU=BOF,OU=Accounts,OU=KADEN,DC=DRUI,DC=PASXO,DC=com
Enabled : True
GivenName : John
Name : John Doe
ObjectClass : user
SamAccountName : john.doe
Surname : Doe
UserPrincipalName : john.doe#BOF.kaden.com
NotExistingAccounts.txt produces
user does not exist
please help 😊
There is a specific set of properties that Get-ADUser will bring for an AD User by default, you need to specify other properties you want to bring using the -Properties parameter (such as Description and mail)
This code sample should bring those properties you're looking for and export the users to a CSV file. Try it out.
Remove Select-Object samAccountName, Description, Mail at the end if you want to bring the default properties plus the ones you needed.
Import-Module ActiveDirectory
$UserList = Get-Content E:\Users\JohnDoe\Desktop\UserList.csv
$hash = #{
Properties = 'Description','mail'
}
$foundUsers = foreach($Item in $UserList)
{
$hash.LDAPFilter = "(|(samAccountName=$item)(name=$item))"
Get-ADUser #hash
if ($user)
{
$user
continue
}
"$item does not exist" |
Out-File E:\Users\JohnDoe\Desktop\NotExistingAccounts.txt -encoding Default -Append
}
$foundUsers | Select-Object samAccountName, Description, Mail |
Export-Csv E:\Users\JohnDoe\Desktop\existingAccounts.csv -NoTypeInformation

Compare User AD and CSV file column Powershell

I'm not really good in Powershell, I try to write a script to compare a column "User" in a CSV with my all user AD.
I need to get all users in the CSV where not in our AD.
Here what I have wrote :
$csvfile = Import-CSV USERAccountstocompare.csv
$alladusers = Get-ADUser -Filter * | Select sAMAccountName
foreach($user in $alladusers){
$userAD = $alladusers.SamAccountName
foreach($usercsv in $csvfile){
if ($usercsv | where {$_.user -ne "$userAD"}){ write "$usercsv"}
else{}
}
}
When I put a write $usercsv before the if command; I get the good user
but after the if, it write all user with #{User= before, like "#{User=username}" so the comparison not working.
You don't need a foreach loop for this; just filter with Where-Object.
Assuming the User column in the CSV contains SamAccountNames:
$csvUsers = Import-Csv -Path 'D:\Test\USERAccountstocompare.csv'
$allADUsers = Get-ADUser -Filter * | Select-Object -ExpandProperty sAMAccountName
$notADUsers = $csvUsers | Where-Object { $allADUsers -notcontains $_.User }
# output on screen
$notADUsers | Format-Table -AutoSize
# output to new CSV file
$notADUsers | Export-Csv -Path 'D:\Test\UsersNOTinAD.csv' -NoTypeInformation
$alladusers = Get-ADUser -Filter * | Select sAMAccountName is not a very good idea if the Domain you are working on is big. Using Where-Object is also not a very good idea for filtering big objects, there was a really cool article in powershell.org where Dave Wyatt and Don Jones explained the different ways of filtering an object and their efficiency, sadly it was removed for some reason.
I would do something like this, assuming your Csv has a column 'User' for each user:
$result=New-Object System.Collections.ArrayList
#result array will be only the user that do not exist in AD
$csvfile = Import-CSV USERAccountstocompare.csv
foreach($line in $csvfile.User)
{
$filter="(|(Name=$line)(samAccountName=$line))"
$adusr=Get-ADuser -LDAPFilter $filter
if(!$adusr)
{
$result.add($line) > $null
}
}
If instead, you wanna have a list of the users that are on the Csv and on AD and those that are only in the Csv you could do something like this:
$result=New-Object System.Collections.ArrayList
#result array will be only the user that do not exist in AD
$csvfile = Import-CSV USERAccountstocompare.csv
foreach($line in $csvfile.User)
{
$filter="(|(Name=$line)(samAccountName=$line))"
$adusr=Get-ADuser -LDAPFilter $filter
if(!$adusr)
{
$result.add(
[pscustomobject]#{
'Not In AD'=$line
}) > $null
}
else
{
$result.add(
[pscustomobject]#{
'In AD and Csv'=$line
}) > $null
}
}

Export Distribution Group

I need to export the following to a csv or excel file
-Distribution Group (PrimarySmtpAddress)
-Distribution Group members and each primarysmtpaddress
I tried adding
Group email: $($group) | PrimarySmtpAddress
in the code below but it does not add it.
#This is what works but is missing
$groups = Get-DistributionGroup -ResultSize Unlimited | Select -ExpandProperty name
ForEach ($group in $groups)
{
"Group Name: $($group)`nGroup Members:`n"
Get-DistributionGroupMember $group |ft name,alias,primarysmtpaddress
}
I am missing the Distribution group primary smtp address?
As Lee_Daily commented, you are stripping out all properties except the Name by doing Select -ExpandProperty name. Next, if you want to export to a CSV file, DO NOT USE Format-Table (ft), because that is only to format the result to the console.
What you should do is create an array of objects and pipe that to the Export-Csv cmdlet, like in the below (untested) code:
$outputFile = '<PATH AND FILENAME FOR THE EXPORTED CSV FILE>'
Get-DistributionGroup -ResultSize Unlimited | ForEach-Object {
# The Identity parameter for Get-DistributionGroupMember specifies the distribution group
# or mail-enabled security group. You can use any value that uniquely identifies the group.
# The cmdlet also accepts the Identity parameter as pipeline input, so
# $_ | Get-DistributionGroupMember will also work.
$Members = Get-DistributionGroupMember -Identity $($_.PrimarySmtpAddress)
foreach ($member in $Members) {
[PSCustomObject]#{
GroupName = $_.DisplayName
GroupAlias = $_.Alias
GroupEmail = $_.PrimarySMTPAddress
MemberName = $member.DisplayName
MemberEmail = $member.PrimarySMTPAddress
# Maybe also add RecipientType to distinguish between users and groups?
# MemberType = $member.RecipientType
}
}
} | Export-Csv -Path $outputFile -NoTypeInformation
Hope that helps

How to get list of selected AD Groups, that a large list of users are members of?

I have the below working script that checks if a large list of users in a CSV file are a member of an AD group and writes the results to results.csv.
Not sure how to convert the script so I can change $group = "InfraLite" to $group = DC .\List_Of_AD_Groups.CSV.
So the script doesn't just return matches for one AD group but so it returns matches for the 80 AD groups contained in the List_of_AD_groups.csv also. Writing a YES/NO for each AD group in a new column in the CSV (or if that's not possible creating a seperate .csv file for each group with results would do also.
I could do this manually by changing the value of $group and export file name, and re-running the script 80 times but must be a quick was with PS to do this?
e.g. results.csv:
NAME AD_GROUP1 AD_GROUP2 AD_GROUP80 etc etc.
user1 yes no yes
user2 no no yes
user3 no yes no
echo "UserName`InfraLite" >> results.csv
$users = GC .\user_list.csv
$group = "InfraLite"
$members = Get-ADGroupMember -Identity $group -Recursive |
Select -ExpandProperty SAMAccountName
foreach ($user in $users) {
if ($members -contains $user) {
echo "$user $group`tYes" >> results.csv
} else {
echo "$user`tNo" >> results.csv
}
}
I played with this for a while, and I think I found a way to get you exactly what you were after.
I think Ansgar was on the right path, but I couldn't quite get it to do what you were after. He mentioned that he didn't access to an AD environment at the time of writing.
Here is what I came up with:
$UserArray = Get-Content 'C:\Temp\Users.txt'
$GroupArray = Get-Content 'C:\Temp\Groups.txt'
$OutputFile = 'C:\Temp\Something.csv'
# Setting up a hashtable for later use
$UserHash = New-Object -TypeName System.Collections.Hashtable
# Outer loop to add users and membership to UserHash
$UserArray | ForEach-Object{
$UserInfo = Get-ADUser $_ -Properties MemberOf
# Strips the LPAP syntax to just the SAMAccountName of the group
$Memberships = $UserInfo.MemberOf | ForEach-Object{
($_.Split(',')[0]).replace('CN=','')
}
#Adding the User=Membership pair to the Hash
$UserHash.Add($_,$Memberships)
}
# Outer loop to create an object per user
$Results = $UserArray | ForEach-Object{
# First create a simple object
$User = New-Object -TypeName PSCustomObject -Property #{
Name = $_
}
# Dynamically add members to the object, based on the $GroupArray
$GroupArray | ForEach-Object {
#Checking $UserHash to see if group shows up in user's membership list
$UserIsMember = $UserHash.($User.Name) -contains $_
#Adding property to object, and value
$User | Add-Member -MemberType NoteProperty -Name $_ -Value $UserIsMember
}
#Returning the object to the variable
Return $User
}
#Convert the objects to a CSV, then output them
$Results | ConvertTo-CSV -NoTypeInformation | Out-File $OutputFile
Hopefully that all makes sense. I commented as much of it as I could. It would be very simple to convert to using ADSI if you didn't have RSAT installed on whatever machine you're running this on. If you need that let me know, and I'll make some quick modifications.
I've also tossed a slightly modified version of this in a Gist for later reference.
The trivial solution to your problem would be to wrap your existing code in another loop and create an output file for each group:
$groups = Get-Content 'C:\groups.txt'
foreach ($group in $groups) {
$members = Get-ADGroupMember ...
...
}
A more elegant approach would be to create a group mapping template, clone it for each user, and fill the copy with the user's group memberships. Something like this should work:
$template = #{}
Get-Content 'C:\groups.txt' | ForEach-Object {
$template[$_] = $false
}
$groups = #{}
Get-ADGroup -Filter * | ForEach-Object {
$groups[$_.DistinguishedName] = $_.Name
}
Get-ADUser -Filter * -Properties MemberOf | ForEach-Object {
$groupmap = $template.Clone()
$_.MemberOf |
ForEach-Object { $groups[$_] } |
Where-Object { $groupmap.ContainsKey($_) } |
ForEach-Object { $groupmap[$_] = $true }
New-Object -Type PSObject -Property $groupmap
} | Export-Csv 'C:\user_group_mapping.csv' -NoType