Ernesto Gallardo
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\All Users2.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($_.BaseNa me)) {
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,
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\All
Get-ChildItem -Path "C:\Jabber Pictures\userid" -Filter *.jpg | Where-Object {$_.BaseName -match '\A\d{7}\Z'} | ForEach-Object {
If ($ht.ContainsKey($_.BaseNa
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,
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The explanation Is the one in my answer. I had to use both in my scenario, (rename and move)
»bp