powershell - Passing arguments to job initialization script -


i have multiple jobs , every job want have same initialization script sets things up. i'd pass arguments initialization script, unfortunately arguments passed using -argumentlist seem accessible in actual job script.

here's example demonstrates argument being accessible in actual script:

function startjob([scriptblock] $script, [string] $name, [scriptblock] $initialization_script = $null, $argument = $null) {     start-job -scriptblock $script -name $name -initializationscript $initialization_script -argumentlist $argument | out-null }  [scriptblock] $initialization_script = {     # argument given startjob should accessible here     param($test)     echo "test: $test" }  [scriptblock] $actual_script = {     param($test)     echo "test: $test" }  startjob $actual_script "test job" $initialization_script "have string in `$initialization_script"  @(get-job).foreach({     # wait job finish, remove , output results     write-host "$($_.name) results:"     receive-job -job $_ -wait -autoremovejob | write-host }) 

how able access arguments passed in $initialization_script?

afaik it's not possible pass parameters initialization scripts. init scripts designed reusable scripblocks load known resources. if can't defined once, it's unique job's scriptblock , doesn't belong in init. script. have few alternatives:

  • if have module (.psm1 , maybe .psd1), place in 1 of module-folders (see $env:psmodulepath paths) write import-module myimportantmodule in initialization script.

  • if can't use solution above, add paramter actual script , pass in path regular argument.

    [scriptblock] $actual_script = {     # argument given startjob should accessible here     param($test, $modulepath)      #import-module $modulepath      echo "test: $test" }  start-job -scriptblock $actual_script -name "test job" -argumentlist "first argument", "c:\mymodule.ps1" 
  • or generate initialization scriptblock in script it's dynamic:

    $modulepath = "c:\mymodule.ps1"  $init = @"  #import-module "$modulepath" #something-else  "@  $initsb = [scriptblock]::create($init) 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -