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

1 comment:

  1. Great tid-bit... wish I found this sooner! Took me a while to realize the issue was calling convention.

    function buildit($x, $y) {

    $configFile = ".\$x.$y.config.ps1"
    # file can be empty, mine have a few vars
    write-host $configFile
    . "$configFile"
    }

    buildit("android", "dev")

    outputs: The term '.\android dev..config.ps1' is not recognized

    ReplyDelete