Link to home
Start Free TrialLog in
Avatar of Robert Van Dyke
Robert Van Dyke

asked on

PowerShell update AD Fields from CSV file

I'm trying to update the employeeID field in Powershell based on a flat csv file from HR.  

The script runs through and even writes out the difference in employee ID's but wont actually update.  Here's a small snippet, I can include the larger script if necessary.  Thanks for looking

#compare AD to HRP before trying to update
IF ($EmpNbr  -ne '' -and $EmpNbr -ne $SAMinAD.employeeID) {
  write-host ("AD empid " + $SAMinAD.employeeID + " : HRP EmpID " + $EmpNbr) |
  Set-ADUser $sam -Replace @{employeeID = EmpNbr}
}

Open in new window

Avatar of oBdA
oBdA

You forgot the "$" in front of "EmpNbr" when defining the hashtable value in Set-ADUser. Your script should throw an error at this about "The term 'EmpNbr' is not recognized as the name of a cmdlet, ...".
Other than that: is "$sam" correct in "Set-ADUser"? In line 2, you're referring to what is probably the AD user object in question, $SAMinAD.
Avatar of Robert Van Dyke

ASKER

I fixed the $ typo that was from manaually copying the script rather than copy/paste.  Still having errors even when I changed $sam to $SAMinAD.

I'll include the entire block if you feel so inclined to take a peek, I feel like this is so close...

###########################################################
# AUTHOR  : Victor Ashiedu, John Weller 
# WEBSITE : iTechguides.com
# BLOG    : iTechguides.com/blog-2/
# CREATED : 08-08-2014 
# UPDATED : 10-01-2017
# VERSION : 1.3
# COMMENT : Sometimes when users are created in Active Directory, some attributes are left blank. 
#           This PowerShel Script updates blank user attributes like email address, physical address
#           Manager and more using a CSV file as imput. 
#           If you find this script useful, please take time to rate it via the link below: 
#           http://gallery.technet.microsoft.com/PowerShell-script-to-376e9462
###########################################################
#SCRIPT BEGINS
#The line below measures the lenght of time it takes to
#execute this script

# Get script Start Time (used to measure run time)
$startDTM = (Get-Date)

#Define location of my script variable
#the -parent switch returns one directory lower from directory defined. 
#below will return up to ImportADUsers folder 
#and since my files are located here it will find it.
#It failes withpout appending "*.*" at the end
#This file is required to update fields for existing users
#Modify this script to create new users in UnifiedGov domain


#$path = Split-Path -parent "G:\AppsData\Adaxes\"
$path = "D:\Appsdata\Adaxes\"

#Create log date and user disabled date

$logdate = Get-Date -Format ddmmyyyy

#Define CSV and log file location variables
#they have to be on the same location as the script

$csvfile = $path + "ExtractFiles\HRPWORKFORCEREPORTSTO_20170105.1b.CSV"
$logfile = $path + "Logs\$logdate.Processlogfile.txt"
$HRP2ADRecords = $path + "Logs\$logdate.HRP2ADWarningsLog.txt"

Write-host    ("HRP2AD Updates starting at: " + $startDTM)
write-output  ("HRP2AD Updates starting at: " + $startDTM) | Out-File $logfile 
write-output  ("HRP2AD Updates starting at: " + $startDTM) | Out-File $HRP2ADRecords 


#Define variable for a server with AD web services installed
#$ADServer = '70411SRV'
#$ADServer = '70411SRV'   # Jeff put in correct ID or account

#define searchbase variable
#$SearchBase = "OU=Deleted IDs APR-JUN,OU=Non-Phone Directory Users,DC=kingston,DC=gov,DC=uk"

#Get Admin account credential
#$GetAdminact = Get-Credential 
#write-host ("Get credential: " + $GetAdminact)

#Import Active Directory Module
Import-Module ActiveDirectory

#Import CSV file and update users in the OU with details from the file
#Create the function script to update the users

write-host    ("Importing file: " + $csvfile + "  at: " + (Get-Date)) 
write-output  ("Importing file: " + $csvfile + "  at: " + (Get-Date)) | Out-File $logfile -Append

# Import-Csv -path $csvfile -Header | `
$HRPfile = Import-Csv -path $csvfile 

# write-host $HRPfile
$i = 0      # count of records read.
$ia = 0     # count of records updated in AD  
$ie = 0     # count of records not found active in AD and no update occurred.  HR team may need to update HRP system.

ForEach ($HRPrecord in $HRPfile){ 
  $i = $i + 1
  #Function Update-ADUsers {
  # ForEach-Object { 
   write-host ("Record: " + $i + " and data: " + $HRPrecord)

  $CompanyType = $HRPrecord."Home Comp"
  $EmpNbr = $HRPrecord.'Emp No'
  $Surname = $HRPrecord.'Last Name'
  $FirstName = $HRPrecord.'First Name'
  $MiddleInitial = $HRPrecord.Middle
  $sam = $HRPrecord.'AD ID'
  $City = $HRPrecord.City
  $Position = $HRPrecord.Position
  $PositionTitle = $HRPrecord."Position Title"
  $FTE = $HRPrecord."FTE"
  $Primary = $HRPrecord."Primary?"
  $Dept = $HRPrecord."Dept"
  $DeptDescription = $HRPrecord."Dept Description"
  $PersType = $HRPrecord."Pers Type"
  $PersonnelTypeDesc = $HRPrecord."Personnel Type Desc"
  $JobClass = $HRPrecord."Job Class"
  $OrgHireDate = $HRPrecord."Org Hire Date"
  $RehireDate = $HRPrecord."Rehire Date"
  $PersClass = $HRPrecord."Pers Class"
  $PersonnelClassDesc = $HRPrecord."Personnel Class Desc"
  $PrimaryEmail = $HRPrecord."Primary E-mail"
  $PersonalEmail = $HRPrecord."Personal E-mail"
  $PrimaryPhone = $HRPrecord."Primary Phone"
  $CellPhone = $HRPrecord."Cell Phone"
  $SupEmpNo = $HRPrecord."Sup Emp No"
  $SupLastName = $HRPrecord."Sup Last Name"
  $SupFirstName = $HRPrecord."Sup First Name"
  $SupMiddle = $HRPrecord."Sup Middle"
  $SupADID = $HRPrecord."Sup AD ID"
  $SupHomeComp = $HRPrecord."Sup Home Comp"
  $SupPosition = $HRPrecord."Sup Position"

#  Write-host ("Fields from HRP file- CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + "***End fields." + (Get-Date))
#  Write-host ("City" + $City )
#  Write-host ($Position +" = Position")
#  Write-host ($PositionTitle + " = Position Title")
#  Write-host ($FTE + " = FTE")
#  Write-host ($Primary +" = Primary?")
#  Write-host ($PersType + " = Pers Type")
#  Write-host ($PersonnelTypeDesc + " = Personnel Type Desc")
#  Write-host ($JobClass + " =Job Class")
#  Write-host ($OrgHireDate + " =Org Hire Date")
#  Write-host ($RehireDate + " =Rehire Date")
#  Write-host ($PersClass + " =Pers Class")
#  Write-host ($PersonnelClassDesc + " =Personnel Class Desc")
#  Write-host ($PrimaryEmail + " =Primary E-mail")
#  Write-host ($PersonalEmail + " =Personal E-mail")
#  Write-host ($PrimaryPhone + " =Primary Phone")
#  Write-host ($CellPhone + " =Cell Phone")
#  Write-host ($SupEmpNo + " =Sup Emp No")
#  Write-host ($SupLastName + " = Sup Last Name")
#  Write-host ($SupFirstName + " = Sup First Name")
#  Write-host ($SupMiddle + " = Sup Middle")
#  Write-host ($SupADID + " = Sup AD ID")
#  Write-host ($SupHomeComp + " = Sup Home Comp")
#  Write-host ($SupPosition + " = Sup Position")

$sam = $sam.replace(' ','')

Try { 
  #$SAMinAD = Get-ADUser -server $ADServer -Credential $GetAdminact -LDAPFilter "(sAMAccountName=$sam)"} 
  $SAMinAD = Get-ADUser -Filter {(SamAccountName -eq $sam) -and (Enabled -eq "True")} -Properties * |
  select generationQualifier, SamAccountName, sn, givenName, middleName, Company, Department, title, employeeType, Manager, telephoneNumber, ipphone, EmailAddress, Enabled, LastLogonDate, whenCreated, accountExpirationDate, description, notes, adminDescription, DistinguishedName, employeeID, employeeNumber, otherMailbox[0], otherTelephone[0], personalTitle[0] 
}
Catch { 
}
Finally {
#  write-host "AD try and catch finally statement."
  }

#Execute set-aduser below only if $sam is in AD and also is in the excel file, else ignore#
If($SAMinAD -ne $null -and $sam -ne '')   {
  $ia = $ia + 1 
  Write-host   ("Active AD record found for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + "***End fields. " + (Get-Date))
  Write-host   (" AD display telenbr: " + $SAMinAD.telephoneNumber)
  write-host   (" mobile: " + $SAMinAD.otherTelephone )
  write-host   (" ipphone: " + $SAMinAD.ipphone ) 
  write-host   (" PersonalEmail: " + $SAMinAD.otherMailbox)
  write-host   (" workemail: " + $SAMinAD.EmailAddress )
  write-host   (" deptname: " + $SAMinAD.Department)
  
  write-output ("Active AD record found for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + "***End fields. " + (Get-Date)) | Out-File $logfile -Append

#compare AD to HRP before trying update
IF ($EmpNbr -ne ''  -and $EmpNbr  -ne $SAMinAD.employeeID)  { 
 write-host ("AD empid " + $SAMinAD.employeeID + " : HRP EmpID " + $EmpNbr) |
 Set-ADUser $SAMinAD -Replace @{employeeID = $EmpNbr} 
 }
IF ($Surname -ne  '' -and $Surname -ne $SAMinAD.sn )  {write-host ("AD lname" + $SAMinAD.sn + ":HRP lname" + $Surname )   }    #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{sn = $Surname }}
IF ($FirstName -ne  '' -and $FirstName -ne $SAMinAD.givenname)  { write-host ("AD fname" + $SAMinAD.givenname + ":HRP fname" + $Firstname )   }   #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{givenName = $FirstName }}
IF ($MiddleInitial -ne  '' -and $MiddleInitial -ne $SAMinAD.middlename )  { write-host ("AD MI " + $SAMinAD.middlename + ":HRP MI " + $Middleinitial )   }     #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{middleName = $Middle }}
IF ($PositionTitle -ne  '' -and $CompanyType -ne "MHNE" -and $PositionTitle -ne $SAMinAD.title )  { write-host ("AD title " + $SAMinAD.title + ":HRP title " + $PositionTitle )   } #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{title = $PositionTitle }}
IF ($DeptDescription -ne  '' -and $DeptDescription -ne  $SAMinAD.department)  { write-host ("AD dept desc " + $SAMinAD.department + ":HRP dept desc " + $DeptDescription )  }  #{ Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{department = $DeptDescription }}
IF ($JobClass -ne  '' -and $JobClass -ne  $SAMinAD.extensionAttribute4)  { write-host ("AD jobclass " + $SAMinAD.extensionattribute4 + ":HRP jobclass" + $JobClass )   }       #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{ExtensionAttribute4 = $JobClass }}
IF ($OrgHireDate -ne  '' -and $OrgHireDate -ne  $SAMinAD.extensionAttribute1)  { write-host ("AD hiredt " + $SAMinAD.extensionAttribute1 + ":HRP hiredt " + $OrgHireDate )   }  #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{ExtensionAttribute1 = $OrgHireDate }}
IF ($PersClass -ne  '' -and $PersClass -ne  $SAMinAD.extensionAttribute3)  { write-host ("AD persclass " + $SAMinAD.extensionAttribute3 + ":HRP persclass " + $PersClass)   }   #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{ExtensionAttribute3 = $PersClass }}
IF ($SAMinAD.email -eq '' -and $PrimaryEmail -ne '')  { write-host ("AD primaryemail " + $SAMinAD.email + ":HRP Primary email " + $PrimaryEmail)   }   #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{EmailAddress = $PrimaryEmail }}
IF ($Dept -ne  '' -and $Dept -ne  $SAMinAD.employeenumber)  { write-host ("AD deptnbr " + $SAMinAD.employeenumber + ":HRP deptnbr " + $Dept )   }        #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{employeeNumber = $Dept }}

#  This is my current bug - .othermailbox[0] is an array and not able to compare it to a HRP string????  
#$TempADemail = $SAMinAD.otherMailbox[0] | write-host ("Pemail: " + $TempADemail)
#IF ($PersonalEmail -ne  '' -and $PersonalEmail -ne  $SAMinAD.OtherMailbox )  { write-host ("AD pemail " + $SAMinAD.OtherMailbox + ":HRP pemail " + $PersonalEmail)   }  #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{OtherMailbox = $PersonalEmail }}
IF ($CellPhone -ne  '' -and $CellPhone -ne $SAMinAD.mobile)  { write-host ("AD pfon " + $SAMinAD.mobile + ":HRP pfon " + $CellPhone )   }    #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{Mobile = $CellPhone }}
IF ($SupADID -ne  '' -and $SupADID -ne  $SAMinAD.Manager)  { write-host ("AD mgr " + $SAMinAD.Manager + ":HRP mgr " + $SupADID )   }      #{Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{manager= $SupADID }}

# write warnings to the log to get phone and email differences manually resolved
IF ($PrimaryPhone -ne  '' -and $PrimaryPhone -ne $SAMinAD.telephonenumber) { 
  #{ Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{telephoneNumber = $PrimaryPhone }}
  write-host ("AD workfon " + $SAMinAD.telephonenumber + ":HRP workphone " + $PrimaryPhone)    
  write-output (" Active AD record w diff workfon for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + " AD workfon: " + $SAMinAD.telephonenumber + " HRP workphone: " + $PrimaryPhone + "***End fields. " + (Get-Date)) | Out-File $HRP2ADRecords -Append
  }

IF ($PrimaryEmail -ne  '' -and $PrimaryEmail -ne $SAMinAD.EmailAddress )  { 
  # { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{EmailAddress= $PrimaryEmail }}
  write-host ("AD workemail " + $SAMinAD.EmailAddress + ":HRP workemail " + $PrimaryEmail )   
  write-output (" Active AD record w diff workemail for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + " AD workemail: " + $SAMinAD.EmailAddress + " HRP workemail: " + $PrimaryEmail + "***End fields. " + (Get-Date)) | Out-File $HRP2ADRecords -Append
  }

#added the 'if clause' to ensure that blank fields in the CSV are ignored.
#the object names must be the LDAP names. get values using ADSI Edit
#IF ($StreetAddress -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{StreetAddress=$StreetAddress} }
#IF ($City -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{l=$City} }
#Replace state with an empty value. Project team want the 'state value blank'
#{ Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -State $null } 
#IF ($PostCode -ne '') { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{postalCode=$PostCode} }
#Country did not accept the -Replace switch. It works with the -Country switch
#IF ($Country -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam  -Country $Country } 
#IF ($Title -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{Title=$Title} }
#IF ($Company -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{Company=$Company} }
#IF ($Description -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{Description='Directorate: ' + $Description} }
#IF ($Department -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{Department=$Department}  }
#IF ($Office -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{physicalDeliveryOfficeName=$Office}  }
#IF ($Phone -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{telephoneNumber=$Phone}  }
#IF ($Mail -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{mail=$Mail}  }
#Manager did not accept the -Replace switch. It works with the -manager switch
#IF ($Manager -ne '' ) { Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Manager $ManagerDN} 
#Set a flag to indicate that the user has been updated on AD.
#When I export, I will omit all users with thie flag enabled 
#Added a condition to the export script to ignore any user with the word 'Google Migrated' on the info (Name) field
#The code below adds the word "Migrated" on the Notes fiels, Tepephone tab of the user. 
#The ldap name for the Notes field is 'info'
#Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{info='Google Migrated'} 
#Change name format to 'FirstName Lastname'
#This is essential because some Sutton users display as sAMAccountName
#Rename-ADObject renames the users in the $DisplayName format

#$newsam = (Get-ADUser -identity $sam -server $ADServer -Credential $GetAdminact).DistinguishedName #Rename-ADObject accepts -Identity in DN format

#Rename-ADObject -server $ADServer -Credential $GetAdminact -Identity $newsam -NewName $DisplayName

#For all users validated as 'Left', disable AD account

#If ($Validation -eq 'Left')
#Disable the user
#{ (Disable-ADAccount -server $ADServer -Credential $GetAdminact -Identity $sam)
#Include disable date stamp on all disabled users
#(Set-ADUser -server $ADServer -Credential $GetAdminact -Identity $sam -Replace @{ipPhone="$userdisableddate"} )
#}

# JAW added for ease of debudding
# $DisplayName + $SAMinAD + " is the userid that was successfully updated in AD" | Out-File $logfile -Append

# Add-Content -path $HRP2ADRecords "User record processsed and re-looping" + $SAMinAD

}
Else

{ #Log error for users that are not in Active Directory or with no Logon name in excel file
  $ie = $ie + 1
  Write-host   ("2No active AD record found for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + "***End fields. " + (Get-Date))
  write-output ("2No active AD record found for CompanyType: " + $CompanyType + " EmpNbr: " + $EmpNbr + " Lname: " + $Surname + " Fname: " + $FirstName + " MI: " + $MiddleInitial + " SAM: " + $sam + "***End fields. " + (Get-Date)) | Out-File $HRP2ADRecords -Append


}


}



   
# Run the function script 
#    Update-ADUsers


#Finish
write-host   ("Total records read: " + $i + " Updated: " + $ia + " and not found in AD records: " + $ie + " ending at " + (Get-Date))
write-output ("Total records read: " + $i + " Updated: " + $ia + " and not found in AD records: " + $ie + " ending at " + (Get-Date)) | Out-File $logfile -Append
write-output ("Total records read: " + $i + " Updated: " + $ia + " and not found in AD records: " + $ie + " ending at " + (Get-Date)) | Out-File $HRP2ADRecords -Append

#The lines below calculates how long it takes to run this script
# Get End Time
$endDTM = (Get-Date)

write-host   ("Elapsed seconds: " + (($endDTM-$startDTM).totalseconds) + ".   Elapsed minutes: " + (($endDTM-$startDTM).totalminutes))
write-output ("Elapsed seconds: " + (($endDTM-$startDTM).totalseconds) + ".   Elapsed minutes: " + (($endDTM-$startDTM).totalminutes)) | Out-File $logfile -Append
write-output ("Elapsed seconds: " + (($endDTM-$startDTM).totalseconds) + ".   Elapsed minutes: " + (($endDTM-$startDTM).totalminutes)) | Out-File $HRP2ADRecords -Append

#SCRIPT ENDS

Open in new window

Line 166 is where the update appears to try and fail.
Try using the SamAccountName property in line 169:
 Set-ADUser $SAMinAD.SamAccountName -Replace @{employeeID = $EmpNbr} 

Open in new window

Still didn't update AD unfortunately.  I took out the @ {} because building an array seemed redundant.

 Set-ADUser $SAMinAD.SamAccountName -Replace employeeID = $EmpNbr

Open in new window


I know get an error Cannot convert the "employeeID" value of type "System.String" to type "System.Collections>hashtable".
Your syntax was correct, the @{} needs to stay in place. Set-ADUser expects a hash table.
If you're having errors when the former command ran, post them.
 Set-ADUser $SAMinAD.SamAccountName -Replace @{employeeID = $EmpNbr} 

Open in new window


Using your code the script runs fine with no errors, but we are not getting any written data to AD?
If you're not getting an error, then the cmdlet should have done its job.
How did you verify that nothing was writtem? You didn't specify the -Server argument for Set-ADUser, so the change could have happened on any DC in your environment, and if you're verifying on another DC, the change might not be replicated yet.
I'm verifying by going in through ADUC and manually checking the records.  

I'm doing this in test so we only have 1 DC that could possibly be connecting too.  I'm at  a loss.
You did a refresh of the OU in ADUC before opening the properties?
You're absolutely certain you're checking the correct account?
What happens if you run the Set-ADUser command directly for the test account?
Set-ADUser TestSamAccountName -Replace @{employeeID = 'Foo'} 

Open in new window

Almost got the issue figured out after throwing away the giant script and starting from scratch, thanks OBdA.  Ill have a few more questions after I get this thing finished.
Ok, I'm able to start importing data from the CSV and am able to write to AD and replace fields.  That's all fine and dandy but some fields we need to restrict writing based on conditions.  

For example HR doesn't manage contractors so these users would either have a blank entry or an "X" for the initials field.  I want to write an If statement that says
IF Middle in CSV is blank replace AD with X
Else Replace AD with CSV Input

foreach ($user in $data){
IF ($user.Middle -eq ""){
Get-ADUser -Filter "SamAccountName eq '$($user.'AD ID')'" |
Set-ADUser -Replace @{initials = "X"}}
Else { Get-ADuser - Filter "SamAccountName -eq '$($user.'AD ID')'"
Set-ADUser -Replace @{initials = "$(user.'Middle')"}
}
}

Open in new window


Right now no matter what initials is being over written by the X, I have a feeling my IF isn't quite correct.  Can anyone help push me in the right direction.
* Since you have the user's SamAccountName anyway, there's no need to first retrieve it and then set it; you can set it directly based on SamAccountName.
* You were missing the pipe at the end of line 5
* You were missing the "$" in front of "user" in the subexpression in line 6
* You don't need quotes and the subexpression in line 6 to start with, you could just assign the variable as it is
* You should indent properly, it makes it easier to identify errors and read your scripts.

That said, try it like this:
ForEach ($user in $data) {
	IF ([string]::IsNullOrEmpty($user.Middle)) {
		$Value = 'X'
	} Else {
		$Value = $user.'Middle'
	}
	Set-ADUser -Identity $user.'AD ID' -Replace @{initials = $Value}
}

Open in new window

Yeah, our test environment isn't configured with internet access so I have been manually copying the script over into the forum field, hence all the errors.  I appreciate your timely responses and for forgiving my beginner mistakes.  I've never had any formal scripting classes and have had some big ideas dumped in my lap as of late.  I'm sure I'll have more questions as I work through the rest of the fields.
Works flawlessly! Now onto more fields. Thanks so much.
How would I go about putting all of my conditions under 1 foreach loop instead of multiples?  This feels like it could be shrunk to one loop.
#Import AD module
Import-Module ActiveDirectory

#Declare variables and set path of HRP CSV  #TODO update location based on test/production
$data = Import-Csv -Path D:\Appsdata\Adaxes\ExtractFiles\HRPWORKFORCEREPORTSTO_20170105.1b.CSV

#ForLoop cycles through each user based on AD and HRP Username comparison and updates EmployeeNumber 
foreach ($user in $data){
    #Get-ADUser -Filter "SamAccountName -eq '$($user.'AD ID')'" |
    Set-ADUser -Identity $user.'AD ID' -Replace @{employeeID = "$($user.'Emp NO')"
    }
}
#ForLoop cycles through each user based on AD and HRP Username comparison and Updates First Name
foreach ($user in $data){
    #Get-ADUser -Filter "SamAccountName -eq '$($user.'AD ID')'" |
    Set-ADUser -Identity $user.'AD ID' -Replace @{givenName = "$($user.'First Name')"
    }
}
#ForLoop cycles through each user based on AD and HRP Username comparison and Updates Last Name
foreach ($user in $data){
    #Get-ADUser -Filter "SamAccountName -eq '$($user.'AD ID')'" |
    Set-ADUser -Identity $user.'AD ID' -Replace @{sn = "$($user.'Last Name')"
    }
}
#ForLoop cycles through each user based on AD and HRP Username comparison and Updates DepartmentNumber
foreach ($user in $data){
    #Get-ADUser -Filter "SamAccountName -eq '$($user.'AD ID')'" |
    Set-ADUser -Identity $user.'AD ID' -Replace @{employeeNumber = "$($user.'Dept')"
    }
} 
<#ForLoop cycles through each user based on AD and HRP Username comparison and Updates
middle initial to X or HRP Data#>
Foreach ($user in $data) {
    IF ([string]::IsNullOrEmpty($user.Middle)) {
            $Value = 'X'
    } Else {
            $Value = $user.Middle
    }
    Set-ADUser -Identity $user.'AD ID' -Replace @{initials = $Value}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial