AD Update from CSV file without SamAccountName - powershell

My goal is to use a CSV file exported by HR without the correct headings to update our AD Users&Computers. Ultimately I would like to update: Department, Description/Job Title, Office, Location, Manager.
I'm not asking you to do this for me, just point me in the right direction and id be really grateful.
Also you will notice there is no SamAccountName, this is by design, because users have the same name so we have had to use the first 2 initials of some users first name followed by the last name.
import-module ActiveDirectory
Import-CSV $data | ForEach-Object {
$Name;expression={($_.'First Name'+' '+$_.'Last Name')}
$displayName;expression={$_.'First Name'+' '+$_.'Last Name'}
$givenName;expression={$_.'First Name'}
$surName;expression={$_.'Last Name'}
$description;expression={$_.'Job Name'}
$office;expression={$_.'Location Name'}
$department;expression={$_.'Department Name'}
$title;expression={$_.'Job Name'}
$manager;expression={$_.'Manager Name'}
}
foreach ($user in $data){
Get-ADUser -Filter "displayName -eq '$($user.$Name)'" | Set-ADUser -Replace #{title = “$($user.$title)”}
}
One of the errors I am getting
The term 'expression=' is not recognized as the name of a cmdlet, function, script file, or operable program.

Your code for the most part is unmanageable. It is easier to redo it in order to
point [you] in the right direction
You over complicated things by trying to rename your values of each row. While you can do that you don't really need to. FWIW you were throwing in syntax from calculated properties.
Import-Module ActiveDirectory
# Path to the CSV file
$filePath = "C:\scripts\ADIntegrationData.csv"
# Import the users
Import-CSV $filePath | ForEach-Object {
# Try and find a matching user
$displayName = "{0} {1}" -f $_.'First Name', $_.'Last Name'
Get-ADUser Get-ADUser -Filter "displayName -eq '$displayName'" | Set-ADUser -Title $_.'Job Name' -WhatIf
}
In the case of Set-ADUser you only have to use the -Add, -Remove and -Replace if the property you want to change is already present. -Title is already support so in that case we use it! Always consult the documentation so check the link for Set-ADUser and look at the attributes that are natively available to change.
You will see the -f formatting operator used here. It is a simple way to work with building complicated strings.
Notice the -WhatIf which will help you test your code before making changes to AD that might be wrong.

Related

Get samaccountname from display name - but with extras

First time poster but site has helped me so much in the past.
We are an MSP and regularly get requests from clients to pull various details off a list of users they send us. Unfortunately though their lists rarely (if ever) contain any unique identifiers for AD such as samAccountName or even e-mail.
So typically I only get their first and last names, job titles etc. and use a slight variation on the below to try and get the required samAccountNames to work in batch modify scripts.
Get Samaccountname from display name into .csv
The problem comes (and caused a big headache recently) when I try to put that output back into a table to line up with the displaynames. As if the script can't find the displayname it just moves onto the next one in the list and puts the samAccountName directly below the last one it found. making it out of line with the displayname column I've put it beside.
My question is is there something I can add to the below script that when an error occurs it simply inputs null or similar into the samAccountName output csv so I could spot that easily in an excel sheet.
Similarly some users have multiple accounts like an admin and non-admin account with the same display name but different samAccountName so it pulls both of them, which is less of a problem but also if there was any way to have the script let me know when that happens? That would be super useful for future.
Import-Module activedirectory
$displayname = #()
$names = get-content "c:\temp\users.csv"
foreach ($name in $names) {
$displaynamedetails = Get-ADUser -filter { DisplayName -eq $name } -server "domain.local"| Select name,samAccountName
$displayname += $displaynamedetails
}
$displayname | Export-Csv "C:\temp\Samaccountname.csv"
So the problem lies in that you rely on Get-ADUser to provide you with user objects and when it doesn't you have gaps in your output. You instead need to create an object for every name/line in your "csv" regardless of whether Get-ADUser finds anything.
Get-Content 'c:\temp\users.csv' |
ForEach-Object {
$name = $_
$adUser = Get-ADUser -Filter "DisplayName -eq '$name'" -Server 'domain.local'
# Create object for every user in users.csv even if Get-ADUser returns nothing
[PSCustomObject]#{
DisplayName = $name # this will be populated with name from the csv file
SamAccountName = $adUser.SamAccountName # this will be empty if $adUser is empty
}
} | Export-Csv 'C:\temp\Samaccountname.csv'

Prepend AD User description with PS - Duplicate Update with ForEach

I've seen many code examples where Get-ADUser can be used to append a description with the following code:
get-aduser username -Properties Description | ForEach-Object { Set-ADUser $_ -Description "$($_.Description) Some more stuff" }
I had thought I could simply invert the order of the code in order to prepend, like so:
get-aduser username -properties Description | ForEach-Object { Set-ADUser $_ -Description "Stuff To Use - $($_.Description)"}
The output then becomes:
"Stuff To Use - Stuff To Use"
In essence, whatever is there to start with is wiped out completely and replaced with a doubled up result of the intended goal.
What am I missing here?
The code is good and it likely ran twice accidentally.
Reset the description, run the code, then refresh Active Directory Users and Computers and recheck.

Compare AD users from CSV to a specific OU

I have a CSV list of usernames from all over my domain, and I'm trying to compare the list against a specific OU and send the matches to another file. I'm brand new to powershell, so after a good amount of research and comparing with other scripts I came up with this:
$users = Import-csv C:\Users\me\Desktop\'RSA.csv'
$(ForEach ($user in $users)
{
Get-AdUser -identity $user -SearchBase "ou=Sub,ou=Root,dc=My,dc=Domain,dc=Name" -Filter *
}) |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
When I run this I get the error "Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument
is null or empty." If I run without the -identity $user it just pulls everything. Any suggestions on how to make this work?
When you are calling Get-ADUser rather than giving it a string with just the user name you are passing in an object with a property called username. You could use Select-Object -ExpandProperty Username or reference the just property.
Import-Csv 'C:\Users\me\Desktop\RSA.csv' |
Where-Object {(!([string]::IsNullorWhiteSpace($_.UserName)))} |
ForEach-Object {
Get-ADUser -Identity $_.UserName
} |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
Notes: Changed to a ForEach-Object loop for readability since it looked like you where trying to mostly use the pipeline. Also added a test to skip blank lines or usernames that are whitespace/empty string. Removed the SearchBase and Filter since you are looking up based on identity can't use those in the command. As there isn't a parameter set that allows you to use all of them. Get-Help Get-ADUser shows the available parameter sets.

I have a .csv with thousands of emails, and I need to use Active Directory to find the state of a particular, custom variable, using powershell

I'm new and don't know enough about powershell.
I've got a .csv that is nothing but "EMAILS" for the header and some 6000 emails under it. (email1#company, email2#company, etc.)
I need to find the state of a particular, custom property for each one.
Individually, I know that I can run
Get-ADUser -Filter {mail -eq 'email#company'} -properties customproperty
in order to find one particular user's state.
I have been hitting my head against a wall trying to make it work with import-csv and export-csv, but I keep getting red all over my console.
Can someone point me an to example where import-csv and export-csv are used properly, with a command run against the contents?
Here's what I would do.
First, fetch all users that have email addresses in AD, and save them into a hashtable. This will make lookups absurdly faster and place less overall load on your domain controller. If you've got 100,000 user accounts it may not be the best option, but I expect that it will be in general.
$ADUsers = #{};
Get-ADUser -Filter "mail -like '*'" -Properties mail, customproperty | ForEach-Object {
$ADUsers.Add($_.mail, $_.customproperty);
}
Now you import the CSV and do lookup using a calculated property with Select-Object, and export it back out.
Import-Csv -Path $InputFile | Select-Object -Property emails, #{n='customproperty';e={$ADUsers[$_.emails]}} | Export-Csv -Path $OutputFile -NoTypeInformation;
So without seeing the code of what you posted, where I think you will run problems is with how interaction of two things.
The first will be that when you use the Import-CSV cmdlet. You will receive an array of objects with a property for each column and not an array of strings.
This is ties into the second part of the issue which is the sensitivity of the AD module filter. But the short answer is don't use {} inside the filter because it will break if you use {mail -eq $ImportedCSV.EMAILS}.
mklement0 has a wonderful answer that goes into the details. But a simple rule of thumb is "double quote outer, single quote" inner.
So you could expand the EMAILS property either with Select-Object -ExpandProperty EMAILS to have an array which works inside {} or you could use "mail -eq '$ImportedCSV.EMAILS'".
Here is an example with both the expansion and using the "property -eq '$variable'" style filter:
Import-CSV C:\Example\Path.csv |
Select-Object -ExpandProperty EMAILS |
ForEach-Object {
Get-ADUser -Filter "mail -eq '$_'" -Properties customproperty
} |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
Please use below code
$csvInput = Import-CSV C:\Example\test.csv
Foreach ($line in $csvinput) {
Get-ADUser -Filter {mail -eq $line.mail} -Properties mail, customproperty |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
}

Powershell pipe variables into get-user command

I am trying to pipe a list of email addresses into a get-user command in powershell
$email = get-content -path "c:\temp\file.csv" get-user -indentity $email | select-object userprincipalname,department,phone,name | format-table | out-file c:\temp\file.txt
Welcome to SO.
Lets see... where to start
Email Address is not one of the value recognized for Identity
It is spelled -identity
Don't use Format-table for object output.
Department is not one of the default values returned.
There is no AD attribute just called phone
It's Get-Aduser not get-user
Don't know if it was just a copy paste accident but you have multiple lines as one.
-Identity expects one value. Not an array of names.
Knowing that lets see if we can take a stab at what you were trying to do. Assuming that your file "c:\temp\file.csv" only contained addresses with no header (since that is how you were treating it.)
Get-Content c:\temp\file.csv | ForEach-Object{
Get-ADUser -Filter "emailaddress -eq '$_'" -Properties department,OfficePhone
} | Select-Object UserPrincipalName,Department,OfficePhone,Name | Export-CSV C:\temp\outputfile.csv -NoTypeInformation
There is no error correction here so you might need to look into an -ErrorAction try/catch combination. I encourage you to look that up on your own.