Skip to main content

Posts

Showing posts from January, 2017

Using functions with PowerShell Background Jobs Part 2 of 2

Yesterday we learned how to use the InitializationScript parameter of Start-Job . Today we are going to allow for further modularization of our code and send multiple functions to Start-Job .  We could very easily send multiple functions in the same script block, but I need to pick and choose which functions I will be working with for each process so I need to be able to send them separately.  Here is our code. $JobFunction1 = {   Function Beep  {     Param ( $Tone )     [ console ]::beep( $Tone , 200 )  } } $JobFunction2 = {   Function Beep2  {     Param ( $Tone , $Time )     [ console ]::beep( $Tone , $Time )  } } $InitializationScript = $executioncontext .invokecommand.NewScriptBlock( " $JobFunction1 $JobFunction2 " ) $JobSplat = @{     Name = "Test1"     InitializationScript = $InitializationScript     ArgumentList = 300 , 400 , 200 } Start-Job @JobSplat -ScriptBlock {             Para

Using functions with PowerShell Background Jobs Part 1 of 2

Happy New Year everyone!  I am spending my New Years’ day working on some code that I’ve been putting off while the family has been in town.  Something about shoveling sunshine as opposed to shoveling snow.  I’m working on expanding some Azure code that I have developed and I’m looking at ways to further modularize the code.  Since I use Background jobs with script blocks to speed the processes that I am running, I’m looking at using the InitializationScript parameter of Start-Job . The InitializationScript parameter allows you to run code before the ScriptBlock parameter runs.  When you include functions inside of it, you are able to place those functions in the same memory that the ScriptBlock will execute in.  Let’s take a look at our code to set this up. First we create a variable that will hold our function that we will call from the background job. $JobFunctions = {   Function Beep  {     Param ( $Tone )     [ console ]::beep( $Tone , 200 )  } }