profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Saturday, December 2, 2017

Renaming files via powershell

Okay, so those of you who are can already rename a bunch of files on your system to something else with powershell can skip it. This is for those who are still trying to get a grip on their powershell. Some of my colleagues are starting with it so it is for them.
I needed to rename a bunch of files on my system. 66 to be exact. I needed to rename them with just an incremental number.


1
2
3
4
5
6
7
8
9
$path = 'C:\Users\loser\Materials\my files'
$items = Get-ChildItem $path
$n = 1
foreach ($item in $items) {
$newname = "$n" + '.jpeg'
Rename-Item $item.FullName -NewName $newname -Confirm:$false
$newname
$n++
}

Now we see here that I have the complete script above.
line1-the path to the folder where all the files are located
line2-this get-childitem and the path from the line 1 gets the all the child items from that path and stores that data into a variable called $items. This will be our iterator.
line3 - let us first set our beginning number to be 1. $n = 1
line4 - here we are iterating through the list of $items
line5 - here we will define or decide what the new name of the $item in the list $items will be. $n was set to 1 so it will be 1.jpeg
line 6 - here i am renaming the $item with the fullname blablablah.jpeg to the newname $newname which we have decided in the line 5
line 7 - here i am just printing out the new name. This line is optional
line 8 - now on when the next time this loop runs we want the value of $n to be 2 or 3, that is increment it by 1. $n++ means $n+1.

No comments:

Post a Comment