List user details from Username - powershell

I am trying to create a script that will check a list of user names and show the user full name and some attribute settings from AD. Basically I have been sent a list of usernames which are just numbers and management want to know the users full name for each username. they also want to know want division they work for.
Below is the script I have created which doesn't work.
$csv = Import-Csv "C:\temp\users.csv"
foreach ($user in $csv) {
$name = $user.myid
Get-ADUser -Filter {EmployeeID -eq $name} -Properties * |
Get-ADUser -Division $user.Programme
} | Export-Csv "C:\Temp\Results.csv"

So I'm working under the assumption that there is a column named myid in your csv file that contains the id you need to be looking up. Assuming that is the case you'll need to make a few changes here. You'll need to remove the second get-aduser as it is not really doing anything for you, and there is no -division switch available to the get-aduser cmdlet, if you need to restrict your results to just a few settings you can do that using the -properties switch and piping to select as shown below. Keep in mind that none of this will matter if the users do not have the "employeeid" and "division" properties set on their AD accounts, which is fairly rare in my experience but if your company does as a matter of policy when creating accounts should be fine. If you replace the get-aduser line in your script with this it should get the account of any user with an EmployeeID property that matches the one in your spreadsheet and then output that person's full name, division, and employeeid to your CSV file.
Get-ADUser -Filter {EmployeeID -eq $name} -Properties "displayname","division","employeeid" | Select-Object "employeeid","displayname","division"

When in doubt, read the documentation. Get-ADUser doesn't have a parameter -Division. You need to select the properties you want in the output file. Also, foreach loops don't pass output into the pipeline. You need a ForEach-Object loop if you want to pass the output directly into Export-Csv:
Import-Csv 'C:\temp\users.csv' |
ForEach-Object {
$name = $_.myid
Get-ADUser -Filter "EmployeeID -eq $name" -Properties *
} |
Select-Object SamAccountName, DisplayName, Division |
Export-Csv 'C:\Temp\Results.csv' -NoType
Otherwise you need to collect the output in a variable:
$users = foreach ($user in $csv) {
$name = $user.myid
Get-ADUser -Filter "EmployeeID -eq $name" -Properties *
}
$users | Export-Csv 'C:\Temp\Results.csv' -NoType
or run the loop in a subexpression:
$(foreach ($user in $csv) {
$name = $user.myid
Get-ADUser -Filter "EmployeeID -eq $name" -Properties *
}) | Export-Csv 'C:\Temp\Results.csv' -NoType

This is a generic code structure that can be adapted for data collection / enumeration and production of CSV files, tailored to your scenario. We use similar at my workplace. It contains some error handling - the last thing you'd want is inaccurate results in your CSV file.
# Create an array from a data source:
$dataArray = import-csv "C:\temp\users.csv"
# Create an array to store results of foreach loop:
$arrayOfHashtables = #()
# Loop the data array, doing additional work to create our custom data for the CSV file:
foreach($item in $dataArray)
{
try
{
$ADObject = Get-ADUser -Filter { EmployeeID -eq $item.MyID } -Properties DisplayName,Division -ErrorAction Stop
}
catch
{
Write-Output "$($item.MyID): Error looking up this ID. Error was $($Error[0].Exception.Message)"
}
if($ADObject)
{
# Create a hashtable to store information about a single item:
$hashTable = [ordered]#{
EmployeeID=$item.myID
DisplayName=$ADObject.DisplayName
}
# Add the hashtable into the results array:
$arrayOfHashtables += (New-Object -TypeName PSObject -Property $hashTable)
}
else
{
Write-Output "$($item.MyID): No result found for this ID."
}
}
# If the results array was populated, export it:
if($arrayOfHashtables.Count -gt 0)
{
$arrayOfHashtables | Export-CSV -Path "C:\Temp\Results.csv" -Confirm:$false -NoTypeInformation
}
As mentioned elsewhere, division isn't a property on an AD object so you might need to lookup this data elsewhere. If you can do that with another line of PowerShell inside your foreach loop, you could add this to your hashtable object like so:
$hashTable = [ordered]#{
EmployeeID=$item.myID
DisplayName=$ADObject.DisplayName
Division=$DivisionFromOtherSource
}

Related

Powershell Script to pull all AD users and last time password was changed and date of change

I am attempting to create a script to extract all AD users from 3 different domains with their last logon date as well as the last time they changed their password and extract it to a CSV. I have the following code:
$data = #()
$domains = "example.exa.com "," example.com",” ex.example.com”
foreach($domain in $domains)
{
$data | Foreach-Object –Process { get-aduser -filter * -server $domains -properties passwordlastset,lastlogondate | select name, passwordlastset,lastlogondate }
$data | Export-csv –Path C:\passwords.csv -notypeinformation
The following code does not produce any errors, but it runs infinitely with no results. Can anyone help with what I am doing wrong?
There are quite a few things wrong with your code:
You define the three domains with leading or trailing spaces
You loop through the $domains using iterating variable $domain, but in the loop you are using the complete array $domains
$data is defined as (empty) array on top, but still you use it to loop through its elements (which aren't there) by piping to Foreach-Object
Try to avoid adding items to an array with += as it needs to reconstruct the entire array in memory on every addition
Try:
$domains = 'example.exa.com','example.com','ex.example.com'
$data = foreach($domain in $domains) {
# just output the objects here, so they will be collected for you in variable $data
Get-ADUser -Filter * -Server $domain -Properties PasswordLastSet, LastLogonDate | Select-Object Name, PasswordLastSet, LastLogonDate
}
$data | Export-csv –Path 'C:\passwords.csv' -NoTypeInformation

Get-AdUser no acepting variable

im trying to pull out all the information regarding my domain admin adminsitrators
#set domains we are going to query
$domains = 'mydomainname.com'
#first here i bring the sam accounts names
Foreach ($domain in $domains)
{
$OUTPUT =Get-AdGroupMember -identity “Domain Admins” -recursive -server $domain |
Select-Object -Property samAccountName|
Select samAccountName;
$Outputs +=$OUTPUT;
$OUTPUT |Export-CSV "C:\File\$($domain).csv" -NoTypeInformation ;
}
$OUTPUT #this print the sam accounts
#here is the problem
Foreach ($user in $OUTPUT)
{
$Users2 =Get-ADUser -Filter "SamAccountName -like '$OUTPUT'" -Properties *
$USER3 +=$Users2;
$Users2 |Export-CSV "C:\File\$($domain)Userpop.csv" -NoTypeInformation ;
}
I think this is a problem with your filter. Try changing that line as follows:
Get-ADUser -Filter " SamAccountName -like `"$($user.samaccountname)`" " -Properties *
It can't be $OUTPUT as that's an array. Your loop variable is $user which is an object so you need the .samaccountname property. The filter needs a string with the -like matching a quoted string, so you need `" to pass the quote through to the final string.
Your CSV output of $user2 may not be what you expect either as each object is output to the same file. Perhaps you mean to have a -Append or write them to different files?
You'll probably want to reset $user3 as well. Perhaps add $user3 = #() before that loop.
You should always try to avoid adding to arrays with $array += $something, because that means the entire array gets rebuild in memory, costing time and resources.
Also, I would advise using more descriptive variable names, so the code will still be understandable after some time.
Then, because you are getting info from different domains, it is important to store the domain name in the first loop together with the samaccount names, so you can use these as -Server parameter in the second loop on Get-ADUser
Try
#set domains we are going to query
$domains = #('mydomainname.com') # since there is only one domain listed, use #() to force it into an array
$domainsAndAdmins = foreach ($domain in $domains) {
# store the SamAccountNames for this domain as objects in an array
$admins = Get-AdGroupMember -Identity 'Domain Admins' -Recursive -Server $domain |
Select-Object -Property SamAccountName
# export this to csv file
$outFile = 'C:\File\{0}.csv' -f $domain
$admins | Export-Csv $outFile -NoTypeInformation
# output an object with both the domain and the array of SamAccountNames
# this will be captured in variable $domainsAndAdmins
[PsCustomObject]#{Domain = $domain; Admins = $admins.SamAccountName }
}
# output on screen
$domainsAndAdmins | Format-Table -AutoSize
# will result in something like
#
# Domain Admins
# ------ ------
# mydomainname.com {jdoe, jbloggs, mpimentel}
# myseconddomainname.com {jdoe, mpimentel}
# next get ALL (?) properties from the users we found
$domainsAndAdmins | ForEach-Object {
$domain = $_.Domain
$result = foreach ($user in $_.Admins) {
Get-ADUser -Filter "SamAccountName -like '$user'" -Server $domain -Properties * -ErrorAction SilentlyContinue
}
$outFile = 'C:\File\{0}_Userpop.csv' -f $domain
$result | Export-Csv $outFile -NoTypeInformation
}

Disable users from valid list

I've got a list of valid users provided by HR. The formatting was not cool, so I managed to get a new file like I wanted: one column, on each line the samaccountname (1st letter of firstname and name).
My file looks like this:
bgates
sjobs
bmarley
epresley
etc.
I'd like to disable users who are NOT in this list. I guess I have to deal with some if stuff, but I don't know how to.
#HariHaran, i have tried this:
#this part works fine
$list = Import-Csv .\listadnames2.csv -Delimiter ";"
$lol =
ForEach ($user in $list)
{
$user.prenom[0] + $user.nom
}
$lol | Out-File .\samaccountnames.csv
$validusers = Import-Csv .\samaccountnames.csv
$fullusers = Get-ADUser -Filter * -SearchBase "OU=USERS,DC=domain,DC=com" -ResultPageSize 0 -Prop samaccountname | Select samaccountname
foreach ($u in $validusers)
if ($u -match $fullusers) {continue} else
{
Set-ADUser -Identity $($._) -Enabled $false -whatif
}
The users list (samaccountnames.csv) you create in $lol is not a CSV file, but simply a text file with all constructed usernames each on a separate line.
Therefore you should read the file using
$validusers = Get-Content .\samaccountnames.csv instead of $validusers = Import-Csv .\samaccountnames.csv.
Then you'll have an array of samaccountnames to work with.
Next, I wonder why you use -ResultPageSize 0.. The default setting is 256 objects per page, so I can only imaging you could need this value to be higher than this default, not less.
(see the docs)
Taken from the part where you read the samaccountnames file, I think this will do the job:
$validusers = Get-Content .\samaccountnames.csv
# property 'SamAccountName' is returned by default as are
# 'DistinguishedName', 'Enabled', 'GivenName', 'Name', 'ObjectClass', 'ObjectGUID', 'SID', 'Surname' and 'UserPrincipalName'
# get the user objects from AD and loop through them to see if they need to be set disabled
Get-ADUser -Filter * -SearchBase "OU=USERS,DC=domain,DC=com" | ForEach-Object {
# the $_ automatic variable now holds an AD user object
# or use if($_.SamAccountName -notin $validusers). Only for PowerShell version 3.0 and up
if ($validusers -notcontains $_.SamAccountName) {
$_ | Set-ADUser -Enabled $false -WhatIf
}
}

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 Active Directory Loop Through All User Properties

I'm currently working on some PowerShell to update Active Directory User Attributes. The script will read the updated attributes from a CSV.
What I would like to achieve is to iterate through users and compare each user attribute against the value stored in the CSV. If the CSV attribute value doesn’t match the user's Active Directory attribute I would like to update the value in Active Directory
At present I can select a user and display the all the properties using the following:
Get-ADUser -Filter "UserPrincipalName -eq '$($upn)'" -Properties * -SearchBase 'DC=core,DC=com'
What I'm struggling on is the ability to loop through all the properties for each user and compare them against the CSV values for that user.
Here is the snippet I'm working from:
# Import CSV into variable $users
$users = Import-Csv -Path 'C:\PowerShell\AD\UserUpdates.csv'
# Loop through each user
foreach ($user in $users) {
#Search in specified OU and Update existing attributes
$userproperties = Get-ADUser -Filter "UserPrincipalName -eq '$($user.UserPrincpalName)'" -Properties * -SearchBase 'DC=core,DC=com'
}
Does anyone know a way of looping through all the user profile attributes for a user?
Any help or guidance would be greatly appreciated?
UPDATE
Ok working on this a bit further, I have made progress but I don't think it's the cleanest way of accomplishing this.
$userproperties = Get-ADUser -Filter "UserPrincipalName -eq '$($upn)'" -Properties * -SearchBase 'DC=core,DC=com' | Select-Object Name,Created, LastLogon,GivenName,SurName,DisplayName,DistinguishedName,UserPrincipleName
This allows me to select items such as the following:
$userproperties.DisplayName
But with this approach I need to list out every attribute I wish to work with. I would prefer to be able to loop across all properties. Maybe I can put all the properties I wish to utulise into an array and loop through that?
this is a way to cycle into the properties of an object (an AD user in this case):
$user = Get-ADUser -Filter "UserPrincipalName -eq '$($user.UserPrincpalName)'" -Properties * -SearchBase 'DC=core,DC=com'
$user | gm | ? membertype -eq property | select -expa name | % { $user.$_ }
in the foreach-object (%) you can add the logic you need to update some proeprty
It's not too hard to loop through all the properties of one entry in the CSV file. The trick is to transform the hashtable you get from looping through the imported
csv data into a PS object, as follows:
# Import CSV into variable $users
$users = Import-Csv -Path 'C:\PowerShell\AD\UserUpdates.csv'
# Loop through each user
foreach ($user in $users) {
#Obtain attributes from corresponding ADuser.
$userproperties = Get-ADUser -Filter '
"UserPrincipalName -eq '$($user.UserPrincpalName)'" `
-Properties * -SearchBase 'DC=core,DC=com'
#Search in specified OU and Update existing attributes
foreach ($prop in $user.psobject.properties) {
Set-variable -name $prop.name -value $prop.value
# Instead of doing a set-variable, you could set the corresponding attribute
# in the appropriate AD.
}
}
Set-ADUser has a -Replace parameter that accepts a hash table of properties and values that you can use to update multiple properties at once. Rather than looping through each property for each user, you can just build that hash table and then do a single update operation. You can make it a little more efficient by just returning the AD User properties you're checking from your CSV. That list of properties can be had by simply getting a property list from the first object in the collection created from your imported CSV file.
# Import CSV into variable $users
$CSVusers = Import-Csv -Path 'C:\PowerShell\AD\UserUpdates.csv'
#Get the list of properties to check
$Properties = $CSVusers[0].psobject.properties.name
# Loop through each user
foreach ($CSVuser in $CSVusers) {
$UpdateProperties = #{}
#Search in specified OU and Update existing attributes
$ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$($CSVuser.UserPrincpalName)'" -Properties $Properties -SearchBase 'DC=core,DC=com'
#Create a hash table of properties that need updated
Foreach ($Property in $Properties)
{
if ($CSVUser.$Property -ne $ADUser.$Property)
{ $UpdateProperties[$Property] = $CSVuser.$Property }
}
#Update user
if ( $UpdateProperties.Count -gt 0 )
{ Set-ADUser $ADUser.DistinguishedName -Replace $UpdateProperties }
}