help me creating scrip to rename files in a folder with name "extAttribute1" to "SAmaccountName"

Hello ,
I have a folder with .jpg files inside. The files are pictures of users  and are named using their correspondent "ext attribute 1" .  I have also exported to a csv file all users inside an OU with Name, SamAccountName, extAttribute1.  extAttribute1 has 7 digits.  
Now, I need to for all files in the folder that have a file name with 7 digits to rename it to it's correspondent SamAccountName . If file name exists with SamAccountName, overwrite it.
I have several powershell commands to obtain .csv with the files name and the other mentioned before with AD account information for users in OU.
Can someone help me to achieve this.
Thanks,
Ernesto GallardoAsked:
Who is Participating?
 
oBdACommented:
This is in test mode and will only display what it would rename. Remove the -WhatIf in line 5 to run it for real.
$ht = @{}
Import-Csv -Path "C:\Temp\Users.csv" | ForEach-Object {$ht[$_.extAttribute1] = $_.SamAccountName}
Get-ChildItem -Path "C:\Folder\jpg"  -Filter *.jpg | Where-Object {$_.BaseName -match '\A\d{7}\Z'} | ForEach-Object {
	If ($ht.ContainsKey($_.BaseName)) {
		Rename-Item -Path $_.FullName -NewName $ht[$_.BaseName] -WhatIf
	} Else {
		Write-Warning "'$($_.Name)': no match in csv!"
	}
}

Open in new window

0
 
Ernesto GallardoAuthor Commented:
Thanks for your quick response, I can't test it right now, but I will later on tonight (I'm on eastern time) I appreciate your help .
0
 
Ernesto GallardoAuthor Commented:
Perfect Solution, extremely fast.
THANK YOU!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.