views:

133

answers:

1

In my quest to improve my PowerShell skills, here's an example of an ugly solution to a simple problem. Any suggestions how to improve the oneliner are welcome.

Mission: trim a huge icon library down to something a bit more manageable. The original directory structure looks like this:

  /Apps and Utilities
    /Compile
      /32 Bit Alpha png
        /Compile 16 n p.png
        /+ 10 or more files
      /+ 5 more formats with 10 or more files each
    /+ 20 or so icon names
  /+ 22 more categories

I want to copy the 32 Bit Alpha pngs and flatten the directory structure a bit. Here's my quick and very dirty solution:

$dest = mkdir c:\icons; gci -r | ? { $_.Name -eq '32 Bit Alph
a png' } | % { mkdir ("$dest\" + $_.Parent.Parent.Name + "\" + $_.Parent.Name); $_ } | gci | % { cp $_.
FullName -dest ("$dest\" + $_.Directory.Parent.Parent + "\" + $_.Directory.Parent) }

Not nice, but it solved my problem. Resulting structure:

  /Apps and Utilities
    /Compile
      /Compile 16 n p.png
      /etc
    /etc
  /etc

How would you do it?

A: 

Three comments:

  • You aren't implicitly sorting your results after your first test. This probably doesn't matter (they will likely come sorted anyway) but since you are building a directory structure based on Parent.Parent... I could conceive a list of PNG images that would cause some sort (no pun intended) of a problem.
  • Maybe I am old fashioned, but I find dir much more readable than gci. In my own scripting I generally try to expand out most aliases as it tends to improve readability and maintainability for those that are newer to PowerShell.
  • Instead of just chaining everything together, it makes sense to break the chunks out into variables and encapsulate this in a cmdlet/function.
Goyuix
Will look into sorting. When writing scripts I do expand most aliases, but I like my oneliners to be concise -- ls (or dir) are much better choices than gci though :).
Bergius