powershell - Settings $_ in a script block invocation -
in complex script, have bunch calls repeat same pattern: prepare,execute,clean.
only execute part different, want define once prepare , clean calls.
to achieve this, i'd wrap in function, having execute part passed parameter.
i tried this:
function somefunc{ param( [scriptblock]$action, [int]$x, [int]$y ) write-host "before" invoke-command -scriptblock $action -pipelinevariable ($x*$y) write-host "after" } somefunc -x 2 -y 4 -action { write-host -foregroundcolor yellow "result $_" }
but not works. $_
empty.
how can reach goal?
you can pass arguments scriptblock not through pipeline arguments in array argumentlist
parameter invoke-command
cmdlet. able access arguments $args variable inside 'process' scriptblock.
function somefunc { param ($x, $y, $sb) write-host "before"; invoke-command -scriptblock $sb -argumentlist @("some string", $x, ($x * $y)) write-host "after"; } somefunc -x 4 -y 2 -sb { foreach ($a in $args) { write-host ("parameter: $a") } }
the output be
before parameter: string parameter: 4 parameter: 8 after
you can include param()
block inside scriptblock. way allows place additional restrictions on arguments, such strong typing
function somefunc { param ($x, $y, $sb) write-host "before"; invoke-command -scriptblock $sb -argumentlist @("not x", $y, ($x * $y)); write-host "after"; } somefunc -x 4 -y 2 -sb { param ([int]$a, $b, $c) write-host ("a {0}, c {1}, b {2}" -f $a, $c, $b)}
the output shows error
before invoke-command : cannot convert value "not x" type "system.int32". error: "input string not in correct format." @ line:4 char:5 + invoke-command -scriptblock $sb -argumentlist @("not x", $y, ($x * $y)); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidargument: (:) [invoke-command], psinvalidcastexception + fullyqualifiederrorid : invalidcastfromstringtointeger,microsoft.powershell.commands.invokecommandcommand after
Comments
Post a Comment