functionpowershellglobal

PowerShell and global functions


Why is the following code not working? According to this article the usage of global should be correct: http://technet.microsoft.com/en-us/library/ff730957.aspx

Function global:writeLog {
    param($logType, $logString, $logFile)

    $fileStream = New-Object IO.FileStream $logFile ,'Append','Write','Read'
    $streamWriter = New-Object System.IO.StreamWriter $fileStream

    $time = get-date -Format "hh:mm:ss"
    $streamWriter.writeLine("[${time}][$logType] ${logString}")

    $streamWriter.close()

}

$temp = {
    writeLog -logType "INFO" -logString "Test" -logFile "d:\scripts\powershell\logtest.txt"
}

Start-Job -ScriptBlock $temp 
get-job | receive-job -AutoRemoveJob -Wait

This is the exception that powershell throws

The term 'writeLog' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (writeLog:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost

Solution

  • PowerShell jobs actually run in a separate PowerShell process. You can see this like so:

    $pid
    Start-Job {$pid} | Receive-Job -Wait
    

    Where $pid is the current PowerShell's process id.

    Anything that needs to be accessed from the script that runs in the job, must be either defined in the scriptblock passed to Start-Job i.e. function defined in the script block or as parameters passed into the script block using the -ArgumentList parameter on Start-Job or the script can dot source another script (or import a module) that contains the functions it needs. Personally, I would put shared functions in a module like Utils.psm1 and then import like so:

    Start-Job {param($scriptdir) Import-Module $scriptdir\Utils.psm1; ...} -Arg $PSScriptRoot