Export multiple outputs within foreach - powershell

I'm looking to export some data, in particular an AD user along with their AD groups.
My current code:
$users = import-csv -path C:\path
foreach ($user in $users) {
$user | select name,SamAccountName | ft
Get-ADPrincipalGroupMembership $user.samaccountname | select name
#export-csv -path C:\path-NoTypeInformation -Append
}
The issue i'm having is whenever I try to export this information i'm only exporting the group output whereas I need the username to see who these groups actually belong to.
Perhaps there's a better method to achieve this?

You may want to use Select-Object to sort of "bind" the information together with a couple of calculated properties referencing the current $user's properties:
foreach ($user in $users) {
Get-ADPrincipalGroupMembership $user.samaccountname |Select Name,#{Name='User';Expression={$user.Name}},#{Name='SAMAccountName';Expression={$user.SAMAccountName}} |Export-Csv -Path C:\path -NoTypeInformation -Append
}
If you want to group the output in the shell by user name but only display the group name, you can use Format-Table Name -GroupBy User:
# collect the information
$groupMemberships = foreach ($user in $users) {
Get-ADPrincipalGroupMembership $user.samaccountname |Select Name,#{Name='User';Expression={$user.Name}},#{Name='SAMAccountName';Expression={$user.SAMAccountName}}
}
# format console output
$groupMemberships |Format-Table Name -GroupBy User
# export
$groupMemberships |Export-Csv -Path C:\path -NoTypeInformation -Append

Related

Powershell - CSV Export formatting

I am trying to get list of AD groups a user is part of and I have a script that works. But I need to show it in a different manner. Currently the script shows a record in one line with username and then multiple group names in the next cell delimited by a semi-colon.
I would like it in a way that all groups are in each seperate row and the username gets repeated.
Example:
DavidChow - Server Admin Group
DavidChow - Desktop Admin Group
DavidChow - Azure Admin Group
NinaChow - Desktop User Group
This is my script:
$UnameList= Import-Csv C:\temp\users_full_list.csv
ForEach ($username in $UnameList){
$groups=Get-ADPrincipalGroupMembership -Identity $username.Identity | select -expand name
$data = [PSCustomObject]#{
samaccountname = $username.Identity
count = $groups.count
memberOf = ($groups -join ';')}
Write-Output $data | Export-Csv C:\Temp\users_full_list_memberships.csv -Delimiter ";" -NoTypeInformation -Append
}
You could create a "data" object for each group of each user, and then export all to CSV at the end:
Import-Csv C:\temp\users_full_list.csv | foreach {
$identity = $_.Identity
Get-ADPrincipalGroupMembership -Identity $identity | foreach {
[PSCustomObject]#{
SamAccountName = $identity
GroupName = $_.Name
}
}
} | Export-Csv C:\Temp\users_full_list_memberships.csv -Delimiter ";" -NoTypeInformation

Using powershell to change attribute

First:
I am complete new to Powershell-Scripting.
Want to change the attribute "preferredLanguage" from some Users via powershell.
The users are written in txt-file
testUser000
testUser001 and so on
My first try was to become a list with users and some attributes:
$users = ForEach ($user in $(Get-Content C:\Temp\users.txt)) {
Get-AdUser $user -Properties Department, Mail, preferredLanguage
}
$users |
Select-Object SamAccountName,Department,Mail, preferredLanguage |
Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
That worked so far:
"SamAccountName","Department","Mail","preferredLanguage"
"tesUser000","dept1","testUser000#domain.com","DE"
"testUser0001","dept2","testUser001#domain.com",
testUser000 has an entry in preferredLanguage
testUser0001 has no entry
That's ok. When I have completed the users.txt, there are more than 100 users without an entry in 'preferredLanguage'
Now I want to change the preferredLanguage and with some investigation in the Internet I made this:
$users = ForEach ($user in $(Get-Content C:\Temp\users.txt)) {
Get-AdUser $user -Properties Department, Mail, preferredLanguage
}
$users |
Set-AdUser $users -Replace #preferredLanguage="DE" |
Select-Object SamAccountName,Department,Mail, preferredLanguage |
Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
When I understand this script right, then it get from my txt-File every user in it with the given attributes then it changes the attribute 'preferredLanguage' from the users in the txt-file and then it select it again then it will save the output in a csv-file.
Maybe someone can look over the script and would be so kind and give me feedback about it or a better way, because Iam too scary to use this script on the AD-Server.
Just a few things:
Get-AdUser $user means you must be sure the user with that identity exists or an exception will be thrown
the syntax for the -Replace operator should be #{preferredLanguage="DE"}
Set-ADUser does not generate any output unless the -PassThru parameter is used.
if you use ForEach-Object, you can do all this in one loop
Try changing the code with this:
(Get-Content C:\Temp\users.txt) | ForEach-Object {
$account = Get-AdUser -Filter "SamAccountName -eq '$_'" -Properties Department, Mail, preferredLanguage -ErrorAction SilentlyContinue
if ($account) {
$account | Set-AdUser -Replace #{preferredLanguage="DE"} -PassThru |
Select-Object SamAccountName,Department,Mail, preferredLanguage
}
else {
Write-Warning "User '$_' does not exist"
}
} | Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
Hope that helps

Foreach in Get-ADUser

I've tried lots of different combinations at this point and I'm coming up dry. I have a CSV file that contains usernames (Users) of people in the format of 117321, which refers to their login name. I'm trying to get the homedirectory path of all these users and export them to a CSV. Here's what I have so far, but it doesn't seem to work. I've even tried filter.
$InputFile = 'C:\Users.csv'
$Users = Import-CSV $InputFile
$OutputFile = 'C:\Directory Results.csv'
$HomeDirOutput = ForEach ($User in $Users) {
Get-ADUser -LDAPFilter "(sAMAccountName=$user)" -Properties homedirectory
}
$HomeDirOutput | Export-Csv $OutputFile -NoTypeInformation
All I'm getting is a blank spreadsheet.
sAMAccountName is a valid value to pass to the -Identity parameter of Get-ADUser. Assuming that the CSV contains a column "AccountName", you should be able to do
Import-CSV -Path $InputFile | ForEach-Object { Get-ADUser -Identity $_.AccountName -Property sAMAccountName,HomeDirectory } | SelectObject -Property sAMAccountName,HomeDirectory | Export-CSV -NoTypeInformation -Path $OutputFile -Append
(after making sure that the output file doesn't already exist).

To obtain the attribute from the CSV list

There is a list of users in CSV:
Name
surname name
I want to get to their posts. I use this script:
$userList = Import-Csv "C:\Scripts\names.csv"
foreach ($User in $userList) {
Get-ADUser -Identity $user.Name -Properties DisplayName, title |
select DisplayName, title |
Export-Csv -Append "C:\Scripts\title.csv" -NoTypeInformation
}
But the script does not find users.
If you are trying to get the users by their Name or DisplayName you will have to go with Filter instead of Identity. The following should work, assuming your actual AD-users Names are in the format of the csv.
$userList = import-csv "C:\Scripts\names.csv"
ForEach($User in $userList){
Get-ADUser -Filter "Name -eq '$($user.Name)'" -Properties DisplayName,title |
select DisplayName,title | Export-CSV -Append "C:\Scripts\title.csv" -NoTypeInformation}

Exporting Membership groups for users from input file

I have this script that reads samaccountnames from a file and outputs the name of the user with its membership information. However, the output file only shows the last record. It seems that my code is overwriting the previous record. What am I missing? Thank you so much.
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name |
export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
}
Export-Csv has an -append parameter, so you could use that. ie it would append to the csv file with every iteration of the loop. You would need to make sure the file didn't exist before you start the loop or it would just get bigger and bigger each time you ran the code.
Another way it to add the items to an object and then export that at the end. ie $username += Get-ADUser......
You are reading a CSV file using Get-Content. This lets me think the file is simply a list of user SamAccountNames, each on a separate line. No headings.
Something like this perhaps:
jdoe
jsmith
If that is the case, read the input file like this:
$users = Get-Content -Path 'C:\MyScripts\UsersInput.csv'
To get an array of user SAMAccountnames.
If however it is a proper CSV file with headers, looking something like this:
"SamAccountName","Email","More","Stuff"
"jdoe","john.doe#yourdomain.com","blah","blah"
"jsmith","jane.smith#yourdomain.com","blah","blah"
Then you should use the Import-Csv cmdlet to get the entries as objects and obtain an array of SamAccountNames from that:
$users = Import-Csv -Path 'C:\MyScripts\UsersInput.csv' | Select-Object -ExpandProperty SamAccountName
Once you have that array, loop through it and get the group membership info for each user
Untested
$result = foreach ($accountName in $users) {
Get-ADUser –Identity $accountName -Properties DistinguishedName, DisplayName |
Select-Object #{Name = 'User'; Expression = {$_.DisplayName}},
#{Name = 'Groups'; Expression = { ( $_ | Get-ADPrincipalGroupMembership | Select-Object -ExpandProperty name) -join ', '}}
}
$result | Export-Csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
You are indeed overwriting the code ForEach user. You included Export-Csv in the ForEach. Instead export the whole array that ForEach creates:
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name
} | export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation