无法在 ScriptBlock 中访问函数

tam*_*bre 5 powershell asynchronous powershell-5.0

我有一个具有一些函数的脚本,然后在使用这些函数的同一个脚本中执行多个作业。当我开始一份新工作时,他们似乎无法在[ScriptBlock]我的工作中接触到。

这是一个演示这一点的最小示例:

# 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
@(Get-Job).ForEach({
    Wait-Job -Job $_ |Out-Null
    Receive-Job -Job $_ | Write-Host
})

# Remove the completed jobs
Remove-Job -State Completed
Run Code Online (Sandbox Code Playgroud)

我在 PowerShell ISE 中收到的错误是:

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
Run Code Online (Sandbox Code Playgroud)

use*_*407 6

Start-Job在单独的 PowerShell 进程中运行作业。因此,作业无权访问调用 PowerShell 会话的会话状态。您需要在每个作业中定义供作业使用的函数。无需重复代码即可实现此目的的一种简单方法是使用-InitializationScript参数,其中可以定义所有常用函数。

$IS = {
    function CommonFunction1 {
        'Do something'
    }
    function CommonFunction2 {
        'Do something else'
    }
}
$SB1 = {
    CommonFunction1
    CommonFunction2
}
$SB2 = {
    CommonFunction2
    CommonFunction1
}
$Job1 = Start-Job -InitializationScript $IS -ScriptBlock $SB1
$Job2 = Start-Job -InitializationScript $IS -ScriptBlock $SB2
Receive-Job $Job1,$Job2 -Wait -AutoRemoveJob
Run Code Online (Sandbox Code Playgroud)