powershell - 无法在 ScriptBlock 中访问函数

标签 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

我在 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

最佳答案

Start-Job在单独的 PowerShell 进程中运行作业。因此,作业无权访问调用 PowerShell session 的 session 状态。您需要在每个作业中定义由作业使用的函数。在不复制代码的情况下做到这一点的简单方法是使用 -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

关于powershell - 无法在 ScriptBlock 中访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39190435/

相关文章:

c# - 如何正确阻止方法直到对象计数器> 0?

powershell - 组合哈希表时 PowerShell 的行为

powershell - 如何使用 PowerShell 由现有提供程序编写自定义事件日志?

powershell - Powershell保持RemoteDrive session 打开

powershell - 如何让这个 PowerShell 脚本更快地解析大文件?

powershell - 使用EWS检查未读的交换邮件数

PowerShell 5.0 DSC 和导入

powershell - 从 PowerShell 中目录中的特定文件夹获取文件

javascript - 使用 async/await 并发启动

Java异步方法执行