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

前端 未结 2 1656
南旧
南旧 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:29

    If you are still new to using start-job and receive-job, and want to debug your function more easily, try this form:

       $createZip = { 
       function createzipFunc {
         param ([String]$source, [String]$zipfile)
         Process { echo "zip: $source`n     --> $zipfile" }
         }
         #other funcs and constants here if wanted...
       }
       # some secret sauce, this defines the function(s) for us as locals
       invoke-expression $createzip
    
       #now test it out without any job plumbing to confuse you
       createzipFunc "abd" "acd"
    
       # once debugged, unfortunately this makes calling the function from the job  
       # slightly harder, but here goes...
       Start-Job -initializationScript $createZip -scriptblock {param($a,$b) `
    createzipFunc $a $b } -ArgumentList "abc","def"
    

    All not made simpler by the fact I did not define my function as a simple filter as you have, but which I did because I wanted to pass a number of functions into my Job in the end.

    Sorry for digging this thread out, but it solved my problem too and so elegantly at that. And so I just had to add this little bit of sauce which I had written while debugging my powershell job.

提交回复
热议问题