I guess you can't just do this:
$servicePath = $args[0] if(Test-Path -path $servicePath) <-- does not throw in here $block = { write-host $servicePath -foreground "magenta" if((Test-Path -path $servicePath)) { <-- throws here. dowork } }
So how can I pass my variables to the scriptblock $block?
To pass the argument in the Invoke-command, you need to use -ArgumentList parameter. For example, we need to get the notepad process information on the remote server.
With invoke-command you are creating a session to another host. You don't push your complete script into the session but only the scriptblock . So you've got to define your function INSIDE of the scriptblock to use it inside it.
In the PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. Syntactically, a script block is a statement list in braces, as shown in the following syntax: {<statement list>}
The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.
Keith's answer also works for Invoke-Command
, with the limit that you can't use named parameters. The arguments should be set using the -ArgumentList
parameter and should be comma separated.
$sb = { param($p1,$p2) $OFS=',' "p1 is $p1, p2 is $p2, rest of args: $args" } Invoke-Command $sb -ArgumentList 1,2,3,4
Also see here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With