Splatting to avoid repetition

Splatting may be used to avoid repetition when a parameter must be optionally passed on to a number of different commands. It is possible to splat more than one set of parameters.

In this example, the ComputerName and Credential parameters are used by two different commands:

# Parameters used to authenticate remote connections
$remoteParams = @{
Credential = Get-Credential
ComputerName = $env:COMPUTERNAME
}
# Parameters which are specific to Test-WSMan
$testWSMan = @{
Authentication = 'Default'
ErrorAction = 'SilentlyContinue'
}
# By default, do not pass any extra parameters to New-CimSession
$newCimSession = @{}
if (-not (Test-WSMan @testWSMan @remoteParams)) {
# If WSMan fails, use DCOM (RPC over TCP) to connect
$newCimSession.Add('SessionOption', (New-CimSessionOption -Protocol Dcom))
}
# Parameters to pass to Get-CimInstance
$getCimInstance = @{
ClassName = 'Win32_Service'
CimSession = New-CimSession @newCimSession @remoteParams
}
Get-CimInstance @getCimInstance

This example takes advantage of a number of features:

  • It is possible to splat no parameters using an empty hashtable (@{})
  • It is possible to test conditions and dynamically add parameters at run time (if needed)
  • It is possible to splat more than one set of parameters into a command

As the preceding example shows, it is possible to dynamically choose the parameters that are passed to a command without having to write the command in full more than once in a script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.34.146