Quantcast
Channel: Shawson's Code Blog » Powershell
Viewing all articles
Browse latest Browse all 2

Powershell folder/ sub folder renaming

$
0
0

I had my first go at powershell today to rename a bunch of folders in a way which I figured would be too fiddly at the standard command line.  I had a bunch of log files in a structure like this;

/RootFolder
  /foldera
    /logs
      /a-random-log.txt
      /some-log-file.txt
  /folderb
    /logs
      /a-file.txt
      /b-file.txt

I basically wanted to recurse each folder and give the files a sensible name, with a view to eventually moving them all into one folder- so I wanted this;

/RootFolder
  /foldera
    /logs
      /foldera-1.txt
      /foldera-2.txt
  /folderb
    /logs
      /folderb-1.txt
      /folderb-2.txt

After some fiddling I came up with this, which I ran straight from the power shell prompt, in the root folder location;

Get-ChildItem | foreach { $id = 1; Get-ChildItem (($_.fullname) + “\logs\”)| foreach { Rename-Item -Path $_.fullname -NewName ($_.Directory.Parent.name + “-” + ($id++).toString() +”.txt”) } }

  1. Get-ChildItem grabs a directory listing of the root folder- the resulting array I then pipe into a foreach loop.
  2. Each iteration of this first loop I reset the counter variable I will use for naming the files.  Then I grab an array of the files inside each of the log folders within the folders I just listed (!) — so this should be a list of the files in foldera/log/ and folderb/log
  3. Finally I perform the rename – I build up the new file name based on this file (the $_ represents the current object in this iteration of a foreach in powershell) directory property (which will = logs) then I do .parent (to grab the parent dir of logs) which gets us to the directory name we actually want.  I string this together with the index number and hard code an extension, as I know all my files are .txt files.

It took a little fiddling, but it was nice to finally use powershell, as there are many people bigging it up on various tech blogs and twitters!

Once I’m this far, the move is just a matter of tweaking what I already have a little..

Get-ChildItem | foreach { Get-ChildItem (($_.fullname) + “\logs\”)| foreach { Move-Item $_.fullname -Destination ($_.Directory.Parent.Parent.fullname) } }

 

Useful; To find the properties available to you, pipe your collection to Select-Object *, which will iterate through each element, giving you a full print out of all of it’s available properties, and their current values.


Viewing all articles
Browse latest Browse all 2

Trending Articles