Monday, August 6, 2018

Forwarding the current cmdlet's arguments to another

One user had a cmdlet that took several parameters (some optional) and wanted to pass all the cmdlet's parameters to a different cmdlet. Their first approach was to use Invoke-Expression. While that is a good way to run a dynamically generated command, there is a simpler method in this case. The call operator supports real bound parameters (not stringified), $PSBoundParameters is a hashtable of the current cmdlet's parameters, and splatting allows using a hashtable as the parameters to a cmdlet. These things together make for a very elegant command:

& $cmdletName @PSBoundParameters

If the calling cmdlet has extra parameters relative to the callee, $PSBoundParameters can be .Clone()'d, then the clone can be edited down and passed on.

No comments:

Post a Comment