Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 532
Matthias Güntert Avatar asked Sep 19 '25 11:09

Matthias Güntert


2 Answers

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
like image 193
Keith Hill Avatar answered Sep 21 '25 03:09

Keith Hill


From the documentation of Start-Job:

A Windows PowerShell background job runs a command "in the background" without interacting with the current session.

Therefor, the current session scope is ignored.

Trivial Solution: Define the function inside the scriptblock.

$JobScript = { 
    function write-log {
        ....
    }
    write-log <parameters>
}

Alternatively, check these related questions:

Powershell: passing parameters to a job

Variables in Start-Job

like image 44
Eris Avatar answered Sep 21 '25 04:09

Eris