Aug 31 2022 07:05 AM - edited Aug 31 2022 07:06 AM
Hi Everyone,
I'm a beginner to PowerShell. I have a scenario where I need to rename a large amount of folders (see below) in to a new name based on a column value in CSV.
Current folders naming (unfortunately these folders already exists and I couldn't think of another way to achieve this other than PS)
My requirement is to rename all above folders to align the SamAccount value for each user in the CSV.
UPN | DisplayName | SamAccount |
email address removed for privacy reasons | Ellen Corey | Ellen.Corey |
email address removed for privacy reasons | Aron Michell | Aron.Michell |
email address removed for privacy reasons | Sam Colins | Sam.Colins |
What would be the best way to do this using PowerShell?
Appreciate your support on this !! Thank you so much
Aug 31 2022 09:47 AM
as I can see, the folder name is UserName with no dot with a number
and the names in the CVS are usernames with a dot in the middle
are all the names following the same naming convention.?
Aug 31 2022 06:15 PM
Aug 31 2022 10:06 PM
SolutionYou can use this code to fix it
$csv=Import-Csv -Path C:\boot\Book3.csv
Foreach ($Name in $csv){
try {
$Filter=$Name.SamAccount.Replace('.','') +'*'
Get-ChildItem -Directory -Path C:\boot -Filter $Filter | Rename-Item -NewName $name.SamAccount
}
catch {
$_.Exception.Message
}
}
replace the Path and you are good to go
Sep 01 2022 02:20 AM - edited Sep 01 2022 02:22 AM
@farismalaeb
This worked like charm! Thanks so much for your prompt response and support to the community !
Just to improve it a bit for everyone's benefit, could we add a line to handle duplicate ? (for instance, if the same name found in the folders, set "2 or 3" at the end).
like - JonDoe-123 , JonDoe-456
Renamed as JonDoe, JonDoe2
Again, thanks very much !
Aug 31 2022 10:06 PM
SolutionYou can use this code to fix it
$csv=Import-Csv -Path C:\boot\Book3.csv
Foreach ($Name in $csv){
try {
$Filter=$Name.SamAccount.Replace('.','') +'*'
Get-ChildItem -Directory -Path C:\boot -Filter $Filter | Rename-Item -NewName $name.SamAccount
}
catch {
$_.Exception.Message
}
}
replace the Path and you are good to go