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).
Related
I have a CSV file containing the samaccount name of some users.
From this list, I want to export the properties of these users to a CSV file.
Kindly share the simplest possible way to do so in Windows Powershell ISE.
I have tried this :
Import-ModuleActiveDirectory
Import-CSV C:\scripts\list.csv | ForEach{Get-ADUser -Identity $samaccountname-Filter*-Properties*|export-csv c:\ADusers.csv
}
Thank you!
You didn't show us the first couple of lines of the CSV file.
A proper CSV file has multiple fields and a header line like this:
"AccountName","EmailAddress"
"doe","john.doe#example.com"
"kent","clark.kent#example.com"
If this is the case, do:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Import-Csv -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.AccountName)'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
If the file you load only has SamAccountNames each listed on a new line, then this is not a CSV file and you should use:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Get-Content -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
As you can see, I'm not using the -Identity parameter here, because in case a user with that SamAccountName is not found, an exception is thrown.
This way, output is only generated when the user actually exists.
Also, it is a bad idea to use -Properties * when you only want some of the properties returned.
Hope that helps
if you wanna do this in the ISE, you probably dont need/want to use oneliner for that.
I would suggest to import the CSV first, and then run foreach.
$list = Import-CSV -path $filePath
$result = New-Object System.Collections.ArrayList
foreach ($name in $list){
$adUser=Get-ADUser -Identity $name
$result += $adUser
}
From here, you can start thinking of error handling etc.
This will help you:
Import-ModuleActiveDirectory
Import-CSV -Path "C:\Scripts\List.csv" | Foreach {
Get-ADUser -Identity $_ -Filter * -Properties *
} | Export-CSV "C:\ADUsers.csv"
Your code was not working because $samaccountname was empty and blank not containing the username. So I replaced it with the automatic variable $_
Put each SamAccountName on its own line in the list file.
Example:
user1
user2
user3
Change list.csv to a text file (list.txt) and try this:
$username = Get-Content "C:\scripts\list.txt"
ForEach($user in $username){
Get-ADUser -Identity $user | Select GivenName,Surname,Initials | Export-CSV -Path "C:\ADUsers.csv"
}
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
The below script gives me the proper input for one account, when multiple accounts are added it does not work. How can I get it to work for all user accounts listed in the csv file?
$csv = import-csv "c:\users.csv"
foreach($user in $csv){
$Displayname = $user.Displayname
Get-aduser -filter {displayname -eq $displayname}`
-Properties displayName,employeeID,mail, "msDS-UserPasswordExpiryTimeComputed","lastLogonTimestamp" |`
select "Displayname","Enabled",#{Name="PasswordExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},#{N='LastLogonTime'; E={[DateTime]::FromFileTime($_.lastLogonTimestamp)}},SamAccountName,employeeID,mail |`
Export-Csv "c:\temp\users1.csv"
}
You need to add the -append switch to your export-csv otherwise the file will be overwritten each time it is looped over leaving details of only the last user in the list
Export-Csv "c:\temp\users1.csv" -append
How I can get the displayname and the office from a samaccountname list (.txt)? After that I want to save the displaynames and the offices to a .csv file. Here is a approach:
$users = Get-Content C:\TMP\test.txt
foreach ($user in $users)
{
Get-ADUser -ldapfilter "(samaccountname=$user)" -Property name, office | Select-Object -Property Name, Office
}
It should look like:
Hope you can help me?
You are asking for the Export-CSV command but from your comments you might be having issues with placement or your construct of foreach.
Lets try this then
$users = Get-Content C:\TMP\test.txt
$users | ForEach-Object {
Get-ADUser -ldapfilter "(samaccountname=$_)" -Property name,office | Select-Object -Property Name,office
} | Export-Csv -Path C:\temp\export.csv -NoTypeInformation
Update from comments
Was having issues understanding your output from the comments which was why I wanted more that just a picture of the headers. I don't an issue with this code and the text should be quoted so special characters, like commas, should not be an issue. Please update you question with the text content of a sample file and your PowerShell version in case that is coming into play.
Use the delimiter parameter at the end
$users = Get-Content C:\TMP\test.txt
$users | ForEach-Object {
Get-ADUser -ldapfilter "(samaccountname=$_)" -Property name,office | Select-Object -Property Name,office
} | Export-Csv -Path C:\temp\export.csv -NoTypeInformation -Delimiter ";"
I'm trying to get the SAMAccountNames of one domain and compare them with their equals from another domain.
To get all users of dc1 I use:
Get-ADUser -Filter * -SearchBase $SearchBase | Select-Object SamAccountName |
Export-Csv -path $exports -encoding "unicode" -notype
and then I import the csv again and try to compare them for any differences
$readthat = Import-CSV $exports -Header SamAccountName | ForEach-Object {
$user1 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes
$user2 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes -Server $dc2
$modified = #{}
$attributes | Where-Object { $user1.$_ -ne $user2.$_ } | ForEach-Object {
$modified[$_] = $user2.$_
}
}
All that works great, except that it's also trying to find the SamAccountName which of course genereates an error because the SamAccountName = SamAccountName doesn't exit.
Any hints on how to avoid this or do you guys have a more elegant solution?
the .csv looks like this:
"SamAccountName"
"foo"
"bar"
Don't use the -Header SamAccountName option on your import-csv should help immensely. The -Header option is for when the CSV file you are importing doesn't have a header. The Export-CSV cmdlet puts the header in there for you, so you don't have to.