RSS

Powershell and splatting: passing switch parameter to another script

21 Sep

I came across the term splatting previously, but never really paid heed to it until recently when I needed to pass a switch parameter as a variable to another script, like this:

param(
[string]$Name,
[string]$Server,
[switch]$SkipHost
)
if ($SkipHost) {$s = "-SkipHost"} else {$SkipHost = ""}
.\script1.ps1 -Name $name $s
.\script2.ps1 -Name $name -Server $server

The line at script1.ps1 obviously don’t work and will cause an error when executed.

Some folks may ask: “why do I need to do this?” Well, splatting is most useful when you have a main script which calls other external scripts. This is where splatting comes in, its the ability to pass parameters into a script using variables. I don’t need to explain the mechanics about it as there are many posts elsewhere devoted to this already. Suffice to say, despite all the fancy ways in which various authors had devoted their time to describe the use of @PSBoundParameter, they are only useful if you are passing ALL the parameters at one go. If one need to pass only one or two of the parameters, @PSBoundParameter probably makes the script more complex.

One way to make this work without @PSBoundParameter is via the Powershell version 1 method:

param(
[string]$Name,
[string]$Server,
[switch]$SkipHost
)
.\script1.ps1 -Name $name -SkipHost:$SkipHost
.\script2.ps1 -Name $name -Server $server
Advertisements
 
Leave a comment

Posted by on September 21, 2015 in powershell, Scripts

 

Tags:

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

 
%d bloggers like this: