Friday, December 3, 2010

Powershell Functions - Evil Calling Convention Problem

In powershell, one might think that calling a function would look like this:

FindReplaceMany_Directory($SubDir, $fileType, $recursive, $findArray, $replaceArray)

given a function like this:
#Find replace files of a certain file type in a given directory.
#$recursive = true to parse sub-dirs as well
#$fileType = ""*.*"", ""*.txt"", etc.
function FindReplaceMany_Directory($dir, $fileType, $recursive, $findArray, $replaceArray)
... (omitted) ...

This is not the correct syntax. But surprisingly, it still works and ONLY the first parameter gets a proper value. Everything else gets a null.

To properly call this function, do this:
FindReplaceMany_Directory $SubDir $fileType $recursive $findArray $replaceArray

Wednesday, December 1, 2010

Mass Rename files

Here is a script I wrote to rename a bunch of pictures I had on my computer. It lets me put a prefix on the front, so that I can tell what it is by the title in the taskbar at the bottom of the computer when the picture previewer is minimized. This script could easily be tweaked for many other mass renaming jobs without much programming knowledge. Enjoy!

=========(Begin File...just name it something.ps1)========================

Write-Host "Tell me a prefix to put on the front of all *.jpg files in this folder:"
$Prefix = (Get-Host).UI.ReadLine()

if($Prefix.Length -gt 0)
$Files = Get-ChildItem *.jpg

foreach($File in $Files)
$NewName = $Prefix + $File.Name

Write-Host "Renaming $File to $NewName"

Rename-Item $File $NewName
Write-Host "No prefix. Doing nothing."

Write-Host "Press any key..."

=========(End File)========================