ICT

[PowerShell]Fetching Rows from CSV File and Execute PowerShell command for setting EmployeeID

NeoSailer 2023. 3. 27. 08:35

[Senario]

HR dept. wants to set employeeID for those who have blank employeeID in AD. They sent me a csv file with column userPrincipalName and EmployeeID. 

 

[Objectives]

- Create PowrShell script which fetchs data from the given csv file from HR department and set employeeID

 

It would be a good chance to maniplate ChatGPT so I asked the AI to generate PowerShell Code

Me:
I am working on Powershell script which fetch data from each row in csv file then execute script with loop function. 
Can you please let me know how to get each line from userprincipalname and employeedID from csv file then execute to set employeedID in AD?


ChatGPT
Certainly! Here's an example PowerShell script that can help you achieve this:

# Import the CSV file
$csv = Import-Csv -Path "C:\Path\To\Your\File.csv"

# Loop through each row in the CSV file
foreach ($row in $csv) {
    # Get the UserPrincipalName and EmployeeID from the current row
    $upn = $row.UserPrincipalName
    $empID = $row.EmployeeID

    # Set the EmployeeID for the user in Active Directory
    Set-ADUser -Identity $upn -EmployeeID $empID

Just modified the path of csv file then test bit then have the PowerShell script working very well.

 

$csv = Import-CSV -path 'C:\PowerShell\SetEmployeeID_temp.csv'

foreach($row in $csv)
{
    $upn = $row.UserPrincipalName
    $empID = $row.EmployeeID
    
    Set-ADUser $upn -EmployeeID $empID
    
    Get-AdUser -Properties SamaccountName,EmployeeID,userprincipalname,primarygroup,legacyExchangeDN,objectcategory -filter "SamAccountName -eq '$upn'" | Select-Object userprincipalname, employeeID
}

PS C:\Users\jaehui.yoon> C:\PowerShell\SetEmployeeID.ps1

userprincipalname                 employeeID
-----------------                 ----------
Christoph.Grobelny@rotork.com     105914    
Thomas.Imgrund@rotork.com         105040    
Andreas.Rosentalski@schischek.com 101191

Good job ChatGPT!

반응형