get-aduser from csv file lastlogon passwordexpire - powershell

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

Related

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).

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

Powershell exporting csv issue

<#
Run the Script On Active Directory to remove disabled users from All Groups and Set description what user was member of group if you have all the disable users in an OU.
Just add -SearchBase "OU=disabled,DC=domain,DC=com" after -filter 'enabled -eq $false'
#>
import-module activedirectory
$users=get-aduser -filter 'enabled -eq $false' -SearchBase "OU=Lockdown,DC=home,DC=ac,DC=uk" -Properties samaccountname,memberof |select samaccountname, #{n=’MemberOf’; e= { ( $_.memberof | % { (Get-ADObject $_).Name }) -join “,” }}
#set description
Foreach ($user in $users)
{ Set-ADUser $user.samaccountname -Replace #{info="Was a member of :- $($user.memberof)"}
# Export the list to csv
$Groups = (Get-ADPrincipalGroupMembership -Identity $user.SamAccountName | Select-Object -ExpandProperty name) -join ','
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | select samaccountname, #{name="Groups";expression={$Groups}} | export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"
# Remove From all the Groups
Get-ADGroup -Filter {name -notlike "*domain users*"} | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False
}
$total = ($users).count
Write-Host "$total accounts have been processed..." -ForegroundColor Green
This script Removes all the groups from Disabled Users (From Disabled OU), It adds the names of those groups to Information Field along with an export of csv with the same information.
Porblem is that the csv is only populated with one user's groupmembership when there are many users in Disabled OU. question is, how do i export all the user and their group membership in a csv format. so i have a list of all the users that have been processed.
I always thought that export-csv will export eveything that powershell processes?
Thanks for your help in advance.
Your script attempts to export a csv for each user:
Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname |
select samaccountname, #{name="Groups";expression={$Groups}} |
export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"
...
}
However, this will mean that only the last user run in this foreach block will have its data written out to a .csv file.
This is because Export-Csv will overwrite the contents of an existing .csv file by default. So every user in your foreach block will overwrite the user before it.
To fix this, add the parameter switch -Append to the end of your Export-Csv command. This will add on each users data to the end of the file rather than overwrite it e.g.
Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname |
select samaccountname, #{name="Groups";expression={$Groups}} |
export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";" -Append
...
}

Powershell Import-CSV and Foreach-Object, excluding with the CSV header

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.

powershell change AD user attribute

I need to search through all users in AD, find their attribute "mail" and in this attribute replace #hell.com to #heaven.com
I'm stuck at exporting and importing to csv...
Import-Module ActiveDirectory
get-aduser -Filter {samaccountname -like "gmaleev"} -properties * | Select-Object SamAccountName,mail | export-csv -NoTypeInformation d:\1.csv
$impfile = "d:\1.csv"
Import-CSV $impFile
foreach ($user in $users)
{
$sam = $user.samaccountname
$email = $user.mail
write-host "User $sam has mail $mail"
}
It doesn't work, why?
The current issue is that you are running a cmdlet to import the data but not saving it. Your ForEach cmdlet is not processing any data so you should have blank output except that of Import-CSV which should be outputing to console.
Also it seems redundant to export the data to import it again. I will presume that you have a reason for exporting it.
Import-Module ActiveDirectory
$impfile = "d:\1.csv"
$results = Get-AdUser -Filter {samaccountname -like "gmaleev"} -properties * | Select-Object SamAccountName,mail
$results | export-csv -NoTypeInformation d:\1.csv
$results | foreach ($user in $users){
$sam = $user.samaccountname
$email = $user.mail
write-host "User $sam has mail $mail"
}
This should address what you are showing. It will get the same data and save it to the variable $results. Export that data and then piping it to the ForEach to process
Your title suggets that you want to change user attributes. To do that you would need to use Set-Aduser. Depending on what your environment is this might not be the best way to manipulate email attributes.