When I wrote this script yesterday I was importing an output from the HR database, then using the field "Contact At:People" (which is their email address) to find a matching email address in AD. When I found a match I wanted to collect some data, Name,SamaAccountName,EmployeeNumber,Managerand the along with some data from the HR database, build a PSObject to output a CSV file. Once I have all this data the plan is to update everyone’s Manager and Employee number in AD from the data held by HR
My problem was the way I was searching is way too slow as it is asking each user in turn every time:
$User=Get-aduser-Filter*-Properties*|Where-Object ($_.Mail -eq$ContactMail)|Select-ObjectName,SamaAccountName,EmployeeNumber,Manager
So I need to pull the data in as a variable with, which runs really fast:
$ADAllStaff=Get-ADUser-Filter*-PropertiesSamAccountName,Manager,Name,mail
And this is where my scripting skills run out. What I need to be able to do is for each row in$AllCYCStaff look for a match to the email address from HR field Contact At:People in $ADAllStaff . Once I find my match get the detail I need for my PSObject
Also is this IF statement doing want I want?
##Only add to the PSObject if either EmployeeNumber or Manager is empty
If {($_.EmployeeNumber -eq"") –or ($_.Manager -eq"")}
This is the full script
##Import the HR data and the data from AD
$AllCYCStaff=Import-csv"C:\PurgeUserRecords\AllCurrentStaffList\CYCEstablishmentAllStaffMarch2015.csv"
$ADAllStaff=Get-ADUser-Filter*-PropertiesSamAccountName,Manager,Name,mail
##Loop through the HR data
$AllCYCStaff|ForEach-Object {
$UpdateFile=new-objectpsobject
##Create these to populate the PSObject and run the search
$ContactMail=$_."Contact At:People"
$ManagerEmpID=$_."Personal Ref:Manager"
$PersonEmpID=$_."Personal Ref"
##This is just a visual indicator that it is still searching
$ContactMail
##This is the search I was doing but it will take a long long time to run through
#$User=Get-aduser -Filter * -Properties * | Where-Object ($_.Mail -eq $ContactMail)| Select-Object Name, SamaAccountName, EmployeeNumber, Manager
##Only add to the PSObject if either EmployeeNumber or Manager is empty
If {($_.EmployeeNumber -eq"") –or ($_.Manager -eq"")}{
Write-Host$_.Name
Write-Host$_.EmployeeNumber
$UpdateFile|add-membernotepropertyAD-SamaAccountName$_.SamaAccountName
$UpdateFile|add-membernotepropertyAD-Name$_.Name
$UpdateFile|add-membernotepropertyAD-EmployeeNumber$_.EmployeeNumber
$UpdateFile|add-membernotepropertyHR-PersonalRef$PersonEmpID
$UpdateFile|add-membernotepropertyHR-Mail$ContactMail
$UpdateFile|add-membernotepropertyHR-PersonalRef:Manager$ManagerEmpID
$UpdateFile|add-membernotepropertyAD-Manager$_.Manager
$UpdateFile|Export-Csvc:\EmpIDUpdate.csv-append
}
}