Removing strings from file names with PowerShell
What happened was we have a few hundred files that is numbered with "1_, 2_, 3_" and so on. We were requested to remove the numberings and I don't wanna rename them one by one!
At first, my first google search worked, which was to remove the first two strings from the file name in a folder:
- Go to the folder with the files for renaming
- Right-click + Shift anywhere in the folder and select Open PowerShell window here option
- Paste the following script
#Remove the first two strings from files
get-childitem *.pdf | rename-item -newname { [string]($_.name).substring(2) }
Yep it worked in removing the first two strings until it gets to a double digit number and the "_" wasn't removed. Well I could arrange the folder according to their numberings as such -> 1-9, 10-99, 100-999 and so on.. but I supposed there's a better way.
I asked ChatGPT and here's what she served:
# Get all files in the current directory
$files = Get-ChildItem
# Loop through each file
foreach ($file in $files) {
# Check if the file name matches the pattern "number_"
if ($file.Name -match '^(\d+)_') {
# Extract the part after the numbering
$newName = $file.Name -replace '^(\d+)_', ''
# Rename the file
Rename-Item -Path $file.FullName -NewName $newName
}
}
This script will only remove the numbering, regardless of the number of digit. I tried it with two methods and it worked. The first one is the same as above, that is to paste the script above in the PowerShell Window.
The second method:
- Save the script in any text editor and save it as file .ps1 file. In this example, I it is 'C:\Scripts\remove_numbering.ps1'
- Right-click + Shift anywhere in the folder and select Open PowerShell window here option
- Paste 'C:\Scripts\remove_numbering.ps1' and press Enter.
Note: This code works only if the file names, after removing the numbering, are unique.
Thoughts -
So... this is my first encounter with PowerShell and it seems like there is for sure a crazy lots of things for me to learn and utilise.
ChatGPT - I'm all for using it to to learn simple programming.