gpt4 book ai didi

Powershell start-job -scriptblock 无法识别同一文件中定义的函数?

转载 作者:行者123 更新时间:2023-12-02 14:13:57 26 4
gpt4 key购买 nike

我有以下代码。

function createZip
{
Param ([String]$source, [String]$zipfile)
Process { echo "zip: $source`n --> $zipfile" }
}

try {
Start-Job -ScriptBlock { createZip "abd" "acd" }
}
catch {
$_ | fl * -force
}
Get-Job | Wait-Job
Get-Job | receive-job
Get-Job | Remove-Job

但是,该脚本返回以下错误。

Id              Name            State      HasMoreData     Location             Command                  
-- ---- ----- ----------- -------- -------
309 Job309 Running True localhost createZip "a...
309 Job309 Failed False localhost createZip "a...
Receive-Job : The term 'createZip' 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.
At line:17 char:22
+ Get-Job | receive-job <<<<
+ CategoryInfo : ObjectNotFound: (function:createZip:String) [Receive-Job], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

start-job的脚本 block 内似乎无法识别函数名称。我也尝试过function:createZip

最佳答案

Start-Job 实际上会启动另一个没有 createZip 函数的 PowerShell.exe 实例。您需要将其全部包含在脚本 block 中:

$createZip = {
param ([String]$source, [String]$zipfile)
Process { echo "zip: $source`n --> $zipfile" }
}

Start-Job -ScriptBlock $createZip -ArgumentList "abd", "acd"

从后台作业返回错误消息的示例:

$createZip = {
param ([String] $source, [String] $zipfile)

$output = & zip.exe $source $zipfile 2>&1
if ($LASTEXITCODE -ne 0) {
throw $output
}
}

$job = Start-Job -ScriptBlock $createZip -ArgumentList "abd", "acd"
$job | Wait-Job | Receive-Job

另请注意,通过使用抛出,作业对象State将为“失败”,因此您只能获取失败的作业:Get-Job -状态失败

关于Powershell start-job -scriptblock 无法识别同一文件中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8750813/

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