Can't rename files, if already exist ,using Powershell

Hello ,
I have a folder with .jpg files inside. The files are pictures of users  and are named using their correspondent "EmployeeID" .  I have also exported to a csv file With  all users inside an OU with Name, SamAccountName, EmployeeID.  EmployeeID 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 this script for it:
$ht = @{}
Import-Csv -Path "C:\Temp\Exportedusers\AllUsers2.csv" | ForEach-Object {$ht[$_.EmployeeID] = $_.SamAccountName}
Get-ChildItem -Path "C:\Jabber Pictures\userid"  -Filter *.jpg | Where-Object {$_.BaseName -match '\A\d{7}\Z'} | ForEach-Object {
      If ($ht.ContainsKey($_.BaseName)) {
            Rename-Item -Path $_.FullName -NewName ($ht[$_.BaseName] + ".jpg") -Force
       
      } Else {
            Write-Warning "'$($_.Name)': no match in csv!"
      }
}

 But It can't rename a file if already exists as "SamAccountName.jpeg"  
I get this error:
"Rename-Item : Cannot create a file when that file already exists."

Can someone help me to achieve this.
Thanks,
Ernesto GallardoAsked:
Who is Participating?
 
Ernesto GallardoConnect With a Mentor Author Commented:
Hello Bp,
Thanks for your response and help, but using "MV" instead was giving me issues with the syntax then. So at the end I ended up doing the process of rename in a different folder and after that moving the files to the final destination with the -force. which overwrite the file also if the creation time differs. If it is the same file it won't move  it and thus won't rename it . leaving it in the folder and giving the error permanently.
Regards
0
 
Bill PrewCommented:
Instead of Rename-Item you should be able to use Move-Item -Force to get this done.


»bp
1
 
Ernesto GallardoAuthor Commented:
The explanation Is the one in my answer. I had to use both in my scenario, (rename and move)
0
All Courses

From novice to tech pro — start learning today.