Powershell start-job -scriptblock 无法识别同一文件中定义的函数? [英] Powershell start-job -scriptblock cannot recognize the function defined in the same file?

查看:35
本文介绍了Powershell start-job -scriptblock 无法识别同一文件中定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.

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 

但是,脚本返回以下错误.

However, the script returns the following error.

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的脚本块中似乎无法识别函数名称.我也试过 function:createZip.

It seems the function name cannot be recognized inside the script block of start-job. I tried function:createZip too.

推荐答案

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

Start-Job actually spins up another instance of PowerShell.exe which doesn't have your createZip function. You need to include it all in a script block:

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

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

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

An example returning an error message from the background job:

$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

另请注意,通过使用 throw 作业对象 State 将失败",因此您只能获得失败的作业:Get-Job -状态失败.

Also note that by using a throw the job object State will be "Failed" so you can get only the jobs which failed: Get-Job -State Failed.

这篇关于Powershell start-job -scriptblock 无法识别同一文件中定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆