Powershell start-job -scriptblock cannot recognize the function defined in the same file?

前端 未结 2 1653
南旧
南旧 2021-02-13 13:54

I have the following code.

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

try {
    St         


        
2条回答
  •  离开以前
    2021-02-13 14:13

    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
    

    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.

提交回复
热议问题