Search code examples
powershelljobs

PowerShell, can't figure out how to pass variables to a job


I have the below piece of script that I am having issues with. It is supposed to use variables assigned outside of a job ($FilePath and $Computer) to gather the hot fixes installed on the specified machine and save that information on the system the script is running on.

In this senario, $host_array only contains 127.0.0.1; so $Computer = 127.0.0.1. The loopback address works with the commands, so aside from the error I am getting (listed below the script); I am not sure what I am doing wrong.

ForEach($Computer in $Global:host_array){
        Start-Job  -ScriptBlock {
            $HotFix=Get-HotFix -ComputerName $Computer 
            $HotFix | Export-CSV "$FilePath\$Computer`_HotFix.csv" -NoTypeInformation
        } -ArgumentList $FilePath $Computer
    }

So far, no file is saved via the Export-CSV and I get the following error:

Start-Job : Cannot bind parameter 'InitializationScript'. Cannot convert the "127.0.0.1" value of type "System.String" to type "System.Management.Automation.ScriptBlock".


Solution

  • Like this:

    $FilePath="$HOME\Documents\"
    $host_array="127.0.0.1"
    
    ForEach($Computer in $host_array){
        Start-Job -ScriptBlock {
            
            $FilePath=$args[0];$Computer=$args[1]
    
            $HotFix=Get-HotFix -ComputerName $Computer 
            $HotFix | Export-CSV "$FilePath\$Computer`_HotFix.csv" -NoTypeInformation
        } -ArgumentList $FilePath,$Computer
    }
    

    Or like this:

    $FilePath="$HOME\Documents\"
    $host_array="127.0.0.1"
    
    ForEach($Computer in $host_array){
        Start-Job -ScriptBlock {
            $HotFix=Get-HotFix -ComputerName $using:Computer 
            $HotFix | Export-CSV "$using:FilePath\$using:Computer`_HotFix.csv" -NoTypeInformation
        }
    }
    

    Global variables are not gonna help you here because a Job's scope is on a complete different process. Also, you might wanna take a look at the ThreadJob module https://learn.microsoft.com/en-us/powershell/module/threadjob/start-threadjob?view=powershell-7.1