tambre tambre - 1 year ago 100
PowerShell Question

Function not accessible in a ScriptBlock

I have a script that has some functions and then multiple jobs in the very same script that use those functions. When I start a new job they don't seem to be accessible in the

that I have for my jobs.

Here's a minimal example demonstrating this:

# A simple test function
function Test([string] $string)
Write-Output "I'm a $string"

# My test job
[ScriptBlock] $test =
Test "test function"

# Start the test job
Start-Job -ScriptBlock $test -Name "Test" | Out-Null

# Wait for jobs to complete and print their output
Wait-Job -Job $_ |Out-Null
Receive-Job -Job $_ | Write-Host

# Remove the completed jobs
Remove-Job -State Completed

The error that I get in PowerShell ISE is:

The term 'Test' 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: (Test:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : localhost

Answer Source

Start-Job run jobs in separate PowerShell processes. So that, jobs do not have access to session state of calling PowerShell session. You need to define functions, which get used by jobs, in every job. An easy way to do that without duplicating the code would be using of -InitializationScript parameter, where all common functions can be defined.

$IS = {
    function CommonFunction1 {
        'Do something'
    function CommonFunction2 {
        'Do something else'
$SB1 = {
$SB2 = {
$Job1 = Start-Job -InitializationScript $IS -ScriptBlock $SB1
$Job2 = Start-Job -InitializationScript $IS -ScriptBlock $SB2
Receive-Job $Job1,$Job2 -Wait -AutoRemoveJob
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download