Sunday, August 16, 2015

PowerShell Tip --> Passing array as an argument to a Job/ ScriptBlock

Hi Readers,

I was working on one of the scripts where I have used Powershell Job but it was failing.

On researching I found the reason, which I am Sharing in this small post as a Tip :)

When passing an argument to a script block you can't just pass-it as below:

-ArgumentList $RSHHsp

This will just process the first element in the multi dimensional array or array.

You need to pass it as :

-ArgumentList (,$RSHHsp) 

This will work perfectly as you will expect.

Here is the example illustration of this scenario:

$process = @("notepad","cdpowermonitor")

Invoke-Command -scriptblock {$($args[0]) | foreach-object {get-process $_ }} –argumentlist $process

Capture

On executing the above script, only Notepad process is shown, I will now execute the same script but will change the -Argumentlist syntax.

$process = @("notepad","cdpowermonitor")

Invoke-Command -scriptblock {$($args[0]) | foreach-object {get-process $_ }} –argumentlist (,$process)

Capture

Now its showing both the processes that are mentioned in the array, so please take care when you are using powershell jobs/scripting blocks.

Regards

Sukhija Vikas

http://msexchange.me

No comments:

Post a Comment