gpt4 book ai didi

powershell - 无法在 ScriptBlock 中访问函数

转载 作者:行者123 更新时间:2023-12-01 00:37:53 26 4
gpt4 key购买 nike

我有一个脚本,它有一些函数,然后在使用这些函数的同一个脚本中有多个作业。当我开始一份新工作时,它们似乎无法在 [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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com