I am trying to write a powershell script that will update employeeID attribute in AD for each user
The script needs to update employeeID from my CSV file
Sample CSV:
user,employeeID
user1,1234567
At least now you are trying some code which looks like it should work. Your logic is sound. Are you sure your CSV does not contain and blanks? Some simple statements could rule those out.
Import-CSV "C:\Scripts\Users.csv" | ForEach-Object {
$User = $_.UserName
$ID = $_.EmployeeID
If($user -and $ID){
Set-ADUser $User -employeeID $ID
} Else {
Write-Warning "User or employee number is null. Check source."
}
The If statement would fail if either $user or $id was null. If that is not the case and your CSV does contain data maybe you are having an encoding issue.
I think it depends on how you're finding the user in Active Directory... You could try something like this:
# import the users
$myUsers = Import-Csv csvFile.csv
# loop through each user and update their employeeID property
foreach ($user in $myUsers)
{
# the Set-ADUser cmdlet requires a type of System.Hashtable<>,
# so let's create one
$updateRecord = #{"EmployeeID"=$user.EmployeeID}
# Set the user attribute
Set-ADUser -Identity $user -Replace #updateRecord
}
This might do the trick. Did you guys modify the AD Schema? Keep in mind that "EmployeeID" is assuming you have an EmployeeID Attribute on your Active Directory users.
Please let me know if it helps!
Related
I have written enough PS code to go through a list of displayNames (e.g "John Smith", "Taylor Hanson" - all stored on seperate lines of a txt file) to spit back enough data into another text file that can be used for mailmerge etc. Convincing thousands of employees to simply update Windows is like breaking stones! It has to be automatted to some degree...
Here is the code... the functions that let the user open a specific text file and later save are out of view...
$displayname = #()
$names = get-content $FileIN
foreach ($name in $names) {
$displaynamedetails = Get-ADUser -filter { DisplayName -eq $name } | Select Name, GivenName, Surname, UserPrincipalName
$displayname += $displaynamedetails
}
$displayname | Export-Csv -NoTypeInformation -path $fileOUT -Encoding UTF8
From time to time, a name might be spelled incorrectly in the list, or the employee may have left the organisation.
Is there any way that a statement such as 'Not Found' can be written to the specific line of the text file if an error is ever made (so that an easy side-by-side comparison of the two files can be made?
For most of the other solutions I've tried to find, the answers are based around the samAccoutName or merging the first and last names together. Here, i am specifically interested in displaynames.
Thanks
You can give this a try, since -Filter or -LDAPFilter don't throw any exception whenever an object couldn't be found (unless you're feeding a null value) you can add an if condition to check if the variable where the AD User object is going to be stored is not null and if it is you can add this "not found" user into a different array.
$domain = (Get-ADRootDSE).DefaultNamingContext
$names = Get-Content $FileIN
$refNotFound = [System.Collections.Generic.List[string]]::new()
$displaynamedetails = foreach($name in $names)
{
if($aduser = Get-ADUser -LDAPFilter "(DisplayName=$name)")
{
$aduser
continue
}
$refNotFound.Add(
"Cannot find an object with DisplayName: '$name' under: $domain"
)
}
$displaynamedetails | Select-Object Name, GivenName, Surname, UserPrincipalName |
Export-Csv -NoTypeInformation -path $fileOUT -Encoding UTF8
$refNotFound # => Here are the users that couldn't be found
Side note, consider stop using $displayname = #() and += for well known reasons.
As for AD Cmdlets, using scriptblock based filtering (-Filter {...}) is not supported and even though it can work, it can also bring you problems in the future.
I am attempting to update AD users based on their employeeID number. It is a reliable key field for our organization.
Every user in this case was created with an employeeID attribute. I am using the same csv for the initial creation (New-ADuser) of users (only setting less attributes), as I am the update (Set-ADUser) of users.
Most of this is pretty straightforward and sourced mostly from here. I successfully import my csv, and can print my variables. My resulting message indicates that when I execute my If/Else, that the "User with ID is not found, or more than one is found", both of which aren't true. I believe my issue to be in this line:
$UserID = Get-ADUser employeeID=$EmployeeId
Here is the entirety of the script. What am I doing wrong here?
# Import AD Module
Import-Module ActiveDirectory
# Import CSV into variable $userscsv
$ADUsers = Import-Csv -Path C:\Scripting\CSVs\UpdateADUsers.csv
foreach ($User in $ADUsers)
{
#Retrieve info from CSV
$Title = $User.Title
$Department = $User.department
$Office = $User.Office
$EmployeeId = $User.EmployeeId
$Manager = $User.manager
$Company = $User.Orglevel02
#get user DN
$UserDN = Get-ADUser -LDAPFilter "EmployeeId=$EmployeeId"
If ($UserDN.Count -eq 1)
{
# Use the Set-ADUser cmdlet to assign the new attribute values.
Set-ADUser -Identity $UserDN -Replace #{title=$Title;physicalDeliveryOfficeName=$Office;manager=$Manager}
}
Else {"User with ID $ID either not found, or more than one user found."}
}
$UserDN = Get-ADUser -LDAPFilter "(EmployeeId=*$EmployeeId*)"
Marks answer contains the major correction needed in your filter.
Each of your search criteria at a minimum must be in a set of parenthesis. Like in the example given on ldapexplorer.com
Equality: (attribute=abc) , e.g. (&(objectclass=user)(displayName=Foeckeler)
Your current example has bad syntax since it is missing braces but does not constitute a failure of the cmdlet, so, nothing ($null) is returned. You have a response to this in comments
I initially tried with that syntax, minus the *wildcard. Results still the same, implying User with ID 1234567 either not found, or more than one user found.
What if you hardcode an employeeID in there for testing?
Get-ADUser -LDAPFilter "(EmployeeId=12345)"
If that works then that tells me something is wrong with your source file. Leading or trailing whitespace or perhaps hidden characters? Either way look at the source to be sure and if you have to use .Trim() for testing as you might not initially see the problem.
Get-ADUser -LDAPFilter "(EmployeeId=$($EmployeeID.Trim()))"
I am trying to write a powershell script that will first import from a CSV file. The CSV file will contain the AD employee number attribute, and also the business unit attribute.
The script needs to find the AD user based on employee number attribute from the CSV, then update the business unit attribute for that user also contained in the CSV file. CSV will look like:
0,1
8022651,Sales & Marketing
So far I have been able to lookup the employee number using this:
$EmployeeNumber='8022651'
get-ADUser -Filter {EmployeeNumber -eq $EmployeeNumber}
I know I can use Import-CSV, but don't know how to piece it all together. Any help would be greatly appreciated.
First we need to get the contents of the csv like so
Import-Csv "path to your csv"
If the business unit is located in the Office field we can update it with set-aduser like so
% { set-aduser $_.0 -Office $_.1 }
The % is short for foreach-object, what this essentially does is grab each user one at a time and change the Office field in AD
if we put $_ into a pipeline it will get the previous information passed through so in this case we're grabbing the "0" and "1" headers from the CSV
Once the users Office has been changed it's nice to see each change so we can use write-host like so
write-host "Changed the office of $($_.0) to $($_.1)
Once again we are using $_.0 and $_.1 to get the headings from Import-Csv but because write-host is based on a string we have to put variables into $( ) for them to display correctly.
Put together it is:
Import-Csv "path to your csv" | % {set-ADUser $_.0 -Office $_.1; write-host "Changed the office of $($_.0) to $($_.1)}
This will
Grab the information from your CSV
->then change info in Active Directory for each person based on the 0 and 1 headers
-->then write on the screen who it changed and what to
I hope this made sense, if not let me know in the comments below.
EDIT:
$csv = Import-Csv "path to your csv"
foreach($usr in $csv) {
get-ADUser -Filter {EmployeeNumber -eq $usr.0} | set-ADUser $_ -Office $usr.1
}
EDIT 2:
$csv = Import-Csv "path to your csv"
foreach($usr in $csv) {
$usrToEdit = $usr.0
$editUsr = Get-ADUser -Filter {EmployeeNumber -eq $usrToEdit}
set-aduser -Identity $editUsr.SamAccountName -Office $usr.1
}
Im not sure why I cannot get this to work, but I have a .csv of employee ID's and I want to add them to an AD group, but I cannot get this to work
Function Sync-ADGroup {
$userIDs = Import-CSV $CSV
foreach($ID in $IDs){
Get-ADUser -Filter "EmployeeID -eq '$ID'" -Properties SAMAccountName
}
}
Then I would add them to the group, but I cannot it to return the ADUserObject. Not sure what I am missing.
You need to reference the property name (column) of the user as it appears in the csv file. For example, if the value in the file is under the EmployeeID header:
foreach($userID in $userIDs)
{
Get-ADUser -Filter "EmployeeID -eq $($userID.EmployeeID)" -Properties SAMAccountName
}
For the above to work your csv file needs to look like:
EmployeeID
1234
2345
3456
Undeclared collection variable is used in foreach loop.
$userIDs = Import-CSV $CSV # Load stuff to "userIDs"
foreach($ID in $IDs){ # Enumerate "IDs", oops, should be "userIDs"
As $IDs is empty a variable, the loop doesn't do much.
In order to avoid this kind of errors, use the strict mode: Set-PSDebug -Strict. This will rise an error for using undeclared variable. (Rant: the strict mode should be the default in Powershell. I set it in my profile and all the scripts I write for good measure.)
I know this has been done to death but im useing this as a learning experience with powershell. Could someone take a look at my code and tell me where i am going wrong? Noob code warning!
#
# Add User to an AD Group
#
#
# get arguements and quit if they dont exist
$CSV = $args[0]
$GROUP = $args[1]
if (! $CSV) {
Write-Host "Please format this command as 'AddUsersToGroup <csv file> <AD group>'"
Write-Host "CSV file must have the header 'UserName' with AD usernames following"
exit
}
# Read csv file for users and add to AD group
Import-module ActiveDirectory
Import-CSV "$CSV" | % {
# Get existing users from AD group
$ExistingGroup = "Get-ADGroupMember $GROUP | Select-Object SamAccountName"
# create new array removing existing users from the csv
$NewGroup = $ExistingGroup | where {$CSV -notcontains $_}
# add the users to the AD Group from the new array
Add-ADGroupMember -Identity $NewGroup -Member $_.UserName
exit
}
try delete double quote here:
$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName
with quote you're assign a string value to variable not the results of your commands