multithreadingpowershellpowershell-module

Issue with Start-ThreadJob ScriptBlock Unable to find powershell script


I am using Start-ThreadJob and ScriptBlock to execute a powershell script in a new thread. It works fine on my local but on the preprod server, I am getting an error.

Code Block where I am initiating a new thread

Start-ThreadJob -InputObject $fileType -ScriptBlock {
          ./Functions/Download-FilesFromFTP.ps1 $args[0] $args[1]  $args[2] $args[3] $args[4] $args[5]
        } -ArgumentList $ftpServer,$user,$password,$completeSourceFolder,$completeStagingFolderPath,$completeLogFolderPath

As mentioned earlier, this code block works perfectly on my local. On Preprod env I get the following error when I display jobs using Get-Jobs command. enter image description here

Powershell version on my local enter image description here

Powershell version on preprod server enter image description here

The version of the module ThreadJob is same on both servers


Solution

  • Start-ThreadJob runs the new thread with the same current location as the caller, which is unrelated to where the executing script is located.

    If you want to refer to a file relative to the script's own location, use the automatic $PSScriptRoot variable, and refer to it in the thread script block via the $using: scope:

    Start-ThreadJob -InputObject $fileType -ScriptBlock {
      & "$using:PSScriptRoot/Functions/Download-FilesFromFTP.ps1" @args
    } -ArgumentList $ftpServer,$user,$password,$completeSourceFolder,$completeStagingFolderPath,$completeLogFolderPath
    

    Note the use of @args in order to also pass all positional arguments, reflected in the automatic $args array, through as individual arguments to the target script via splatting.