Saturday, February 24, 2007

Moving files with Powershell

After I reinstalled my computer all the fonts I had gotten of design magasines CDs were gone. I had used one of the fonts in a t-shirt design which was now broken so I had to get them back on my PC. It had been a real pain getting them off the CDs in the first place since most of the mwere either zipped or in a folder and since Vista cannot have folders in its fonts folder (which in itself is stupid) then I had to go through each folder an manually copy the file I wanted to the system Font folder.

Not this time...

The culpits were a selection of fonts from FG. I put all those folders in a new folder:
C:\FGfontTest> and created a sub-folder C:\FGfontTest\OTFonts>
Here is the content of one of those font folders

PS C:\FGfontTest\FGAddiction> ls

Directory: Microsoft.PowerShell.Core\FileSystem::C:\FGfontTest\FGAddiction

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 4/22/2006 5:47 PM 4036 FGAddiction.afm
-a--- 4/22/2006 5:47 PM 481 FGAddiction.inf
-a--- 4/22/2006 5:47 PM 55080 FGAddiction.otf
-a--- 4/22/2006 5:47 PM 66649 FGAddiction.pfb
-a--- 4/22/2006 5:47 PM 731 FGAddiction.pfm
-a--- 4/22/2006 5:44 PM 84604 FGAddiction.ttf
-a--- 5/16/2006 6:52 PM 961 fontgarden.txt

I wanted to move all the OTF files to the OTFonts folder. After quite a bit of mocking around I finally got it to work with this script:
PS C:\FGfontTest> Get-ChildItem ./f* -recurse -include *.otf | Move-Item -dest C:\FGfontTest\OTFonts

I didn't come up with this all by myself. My first attempts were along the lines of
PS C:\FGfontTest> foreach ($d in dir f* )
>> { Move-Item $d C:\FGfontTest\OTFonts -filter *.otf }

which did not work.

Finaly example 4 in Get-Help Move-Item -detailed got me unblocked. Get-Childitem (alias is GCI) has a parameter called -recurse which essentially lets you do what I tried to do in the foreach loop only it can dig into arbitrary levels of folders.

Anyway, fonts are moved and now backed up so I won't have to go thorough this next time I install a PC. The cool thing is that Powershell let me do do a repetivie task across many folder with one line of code


1 comment:

  1. When you have a hammer, everything looks like a nail. I could have done the smaething with the built in search in Vista. I could have searched for .otf selected the files and copied them to the folder I wanted.

    Ohh well. It was good times to do it in Powershell