'Trying to rename multiple files with seperate file extensions
I'm trying to create a Powershell script that renames 2 seperate file extentions in a folder.
The file extensions are .dwg and .upd, however with my current script it only works for a single file extension and when I try to add the 2nd as I've seen others show, it doesnt work.
$curDir = Get-Location
Get-ChildItem $curDir *.dwg,*.upd |
Foreach-Object { Rename-Item $_.FullName ($_.FullName -replace "-_P\d+","" -replace "_X\d","")
Seperate, the .upd and .dwg work, but if I combine the 2 extensions in the script, the script stops working
Example name: P220529-50-ST.001-007-PRD-_P220529-1000_X1-R00.dwg/upd
Any help would be appreciated.
Solution 1:[1]
The -Filter parameter on Get-ChildItem can only be used on a single pattern. If your script is to recurse through subfolders, you could use parameter -Include for that, but since you are not recursing, I'd do this:
(Get-ChildItem -Path $curDir -File) |
Where-Object { $_.Extension -match '\.(dwg|upd)'} |
Rename-Item -NewName {$_.FullName -replace "-_P\d+|_X\d"} -WhatIf
You can remove the -WhatIf safety switch after you have confirmed the messages in the console do lead to the wanted replacements. With that switch, nothing gets renamed, it will only show you what would happen.
The brackets around the Get-ChildItem part is to make sure that completes before sending the results through the pipeline. Without that, chances are it will also pick up files that have already been renamed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Theo |
