Passing parameters to a script block

Passing parameters to a scriptblock seems to be an issue at the moment.

Consider a simple scriptblock

Invoke-Command -ScriptBlock {Get-Process}

How can you modify that to parameterise the processes that are returned.

Its a two step process. Add a parameter block to your script block and secondly pass the correct values to the scriptblock

Invoke-Command -ScriptBlock {
   param ($proc )
   Get-Process -Name $proc
} -ArgumentList “power*”

If you want to pass an array of values to the scriptblock you have 2 options. First abandon the named parameter

$p = (“power*”, “win*”)

Invoke-Command -ScriptBlock {
   
   Get-Process -Name $args
} -ArgumentList $p

if you use $args then all arguments are available through the array

Scriptblocks unravel the array of arguments so if you want named parameters then you need to force the scriptblock to accept an array by using the unary comma operator

$p = (“power*”, “win*”)

Invoke-Command -ScriptBlock {
   param ($proc )
    
   Get-Process -Name $proc
} -ArgumentList (,$p)

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

One Response to Passing parameters to a script block

  1. skolvikings says:

    What about the $Using:Variable syntax. That’s what I’ve been using since 3.0 was released.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s