Link to home
Start Free TrialLog in
Avatar of Ernesto Gallardo
Ernesto GallardoFlag for United States of America

asked on

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,
Avatar of Bill Prew
Bill Prew

Instead of Rename-Item you should be able to use Move-Item -Force to get this done.


»bp
ASKER CERTIFIED SOLUTION
Avatar of Ernesto Gallardo
Ernesto Gallardo
Flag of United States of America image

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
Avatar of Ernesto Gallardo

ASKER

The explanation Is the one in my answer. I had to use both in my scenario, (rename and move)