-1

This should be a quite obvious question... and I have looked into the proposed "duplicate" answers... No way... Only my "hardcoded solution works :-( I just would like to have one parameter (the path) in a Start-Job - ScriptBlock {} command. Here is my scenario:

$MyVariable = "C:\TestPath\Load.ps1"
Start-Job -ScriptBlock { C:\TestPath\Load.ps1 ; while($true) { Get-DataX | Add-ToTable "XXX" ; Start-sleep -s 120}}

This works fine, but is hardcoded; Here are few of the many solutions I tried without success:

Start-Job -ScriptBlock { Get-ChildItem "$MyVariable" ; while($true) { Get-DataX | Add-ToTable "XXX" ; Start-sleep -s 120}}
Start-Job -ScriptBlock { param($MyVariable) Get-ChildItem "$MyVariable" ; while($true) { Get-DataX | Add-ToTable "XXX"; Start-Sleep -s 10 }} -Name MyTest #-ArgumentList @($MyVariable)
Start-Job -ScriptBlock { Get-ChildItem "$MyVariable" ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}}
Start-Job -ScriptBlock { "$MyVariable" ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}}
Start-Job -ScriptBlock { '$MyVariable' ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}}
Start-Job -ScriptBlock { using:$MyVariable ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}}
Start-Job -ScriptBlock { "using:$MyVariable" ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}}
Start-Job -ScriptBlock { $args[0] ; while($true) { Get-DataX | Add-toTable "XXX" ; Start-sleep -s 10}} -Argumentlist@($MyVariable")

But none of them work... So, how do I pass $MyVariable inside my Start-Job -ScriptBlock {...} line ? Maybe my problem comes from somewhere else ? Ideas are more than welcome...

Thanks !

Philippe

Philippe
  • 103
  • 1
  • 1
  • 8

1 Answers1

0

This should be looking like this:

Start-Job -ScriptBlock {
    param($MyVariable) 
        Get-ChildItem $MyVariable; 
        while($true) 
        { Get-DataX ; Start-sleep -s 120}
    } -ArgumentList $MyVariable

Here is a great article that will help you to learn more about script blocks in Powershell.

Kirill Pashkov
  • 3,118
  • 1
  • 15
  • 20