Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to a scriptblock in powershell

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?

like image 928
dexter Avatar asked May 02 '13 20:05

dexter


People also ask

How do you pass arguments to invoke in PowerShell?

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.

How do you call a function in PowerShell Scriptblock?

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.

What is Scriptblock in PowerShell?

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>}

How does $_ work in PowerShell?

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.


1 Answers

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.

like image 124
Lars Truijens Avatar answered Sep 19 '22 17:09

Lars Truijens