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.

 

Tech Wizard

https://techwizard.cloud

https://syscloudpro.com/

 

Advertisement

2 thoughts on “PowerShell Tip –> Passing array as an argument to a Job/ ScriptBlock

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s