In a directory, I have some .jpg
files.
-
The file names are integers starting from
1.jpg
to150.jpg
. -
I would like to subtract
1
from each file name. -
So the file names would be
0.jpg
to149.jpg
.
I know how to replace some characters in the file name using PowerShell
.
How can I achieve this with Powershell
?
Following are the Powershell
scripts which I tried.
Powershell Script
gci *.jpg | rename-item -newname {[integer]($_.name -replace ".JPG", "")-1}
And:
gci *.JPG | rename-item -newname { (([convert]::ToInt32($_.name, 10)) - 1) + ".JPG"}
Best Answer
File names should be like 0.jpg to 149.jpg
Use the following PowerShell command:
Notes:
$count=0
start counting from0
.$_
represents each item passed to the rename-item command via the pipe|
from thedir
command.foreach-object
allows you to set a variable ($count
) before looping through each file in the directory (matching*.jpg
) and then perform an action (rename-item
) for each matching item.To sort the
dir
output in a "natural" sort order, we use:Example:
Source: Batch File Rename with Windows PowerShell. Script has been tweaked to match the requirements of the question.
Source: How to sort by file name the same way Windows Explorer does? answer by Roman Kuzmin for natural sorting.