PoshRSJob icon indicating copy to clipboard operation
PoshRSJob copied to clipboard

Is there a way to pass an intialization script to Start-RSJob cmdlet?

Open singhkays opened this issue 7 years ago • 3 comments

Do you want to request a feature or report a bug? Feature

I have an existing PowerShell script that makes use of Start-Job cmdlet that I'd like to convert to using runspaces for the benefits of runspaces. Is there a way to pass in the initialization script? Current code looks something like below

Please provide a code example showing the issue, if applicable:

$initScriptString = @" ......
.....
...
....
"@

$initScriptBlock = [ScriptBlock]::Create($initScriptString);
Start-Job -InitializationScript $initScriptBlock ...

singhkays avatar May 05 '17 00:05 singhkays

there is a -PSSnapinsToImport, -ModulesToImport, -FunctionsToLoad so InitializationScript doesn't needed if you want to emulate init script there is example

PS C:\> $s = 'function test() { "Its a test" }'
PS C:\> $sb = [scriptblock]::create($s)
PS C:\> . $sb
PS C:\> test
Its a test
PS C:\> Start-RSJob -functionstoload test { test; 'myscript'; }

MVKozlov avatar May 05 '17 20:05 MVKozlov

Thanks for the example @MVKozlov!

Just to make sure I understand correctly, in the below code the part between the { } is the scriptblock passed to the Start-RSJob cmdlet? and it's executing the function test in each iteration of the job?

Start-RSJob -functionstoload test { test; 'myscript'; } 

singhkays avatar May 05 '17 20:05 singhkays

Yes. This is generic examle how you can convert you existing init. Script into function(add function declaration at beginning), load it and use. But I dont' know what your init script do. May be you doesn't need it at all if it only load snapins, modules and functions. Or may be it's code can be moved right into main scrpitblock

MVKozlov avatar May 06 '17 06:05 MVKozlov