Share via


How to pass a param to script block when using invoke-command

Question

Tuesday, May 4, 2010 9:29 AM

Example:

invoke -computername $temp -scriptBlock {How to pass the $temp value in here}

All replies (6)

Tuesday, May 4, 2010 11:41 AM ✅Answered | 5 votes

You need to use ArgumentList parameter  to include the values of local variables in a command run on a remote computer.

Invoke-Command -ComputerName $Computer -ScriptBlock {param($comp) write-host "This script is running on machine: $Comp" } -ArgumentList $Computer

Aleksandar Nikolić http://powershellers.blogspot.com http://twitter.com/alexandair


Wednesday, May 5, 2010 12:59 AM ✅Answered | 4 votes

I use $ExecutionContext.InvokeCommand.NewScriptBlock() to do what you are trying to do:

 

$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("write-host "This script is runnong on machine: $Computer")

Invoke-Command -ComputerName $Computer -ScriptBlock $scriptblock

 

I put together a blog post that discusses dynamic code in scriptblocks.  I do, however, like Aleksandar's suggestion to use -ArgumentList parameter.  It's useful for quick problems like yours, but if you are doing a rather large dynamic scriptblock it is not as effective as using NewScriptBlock().

http://powertoe.wordpress.com/2010/02/10/dynamic-code-in-powershell/

 


Wednesday, May 5, 2010 9:56 AM ✅Answered

Nice. I've learnt something new.

One thing to be careful about - outer quotes should be a double, and inner quotes a single ones.

PS[39]>$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("write-host 'This script is running on machine: $Computer'")

 

Aleksandar Nikolić http://powershellers.blogspot.com http://twitter.com/alexandair


Tuesday, May 4, 2010 10:44 AM

When Running the Invoke-Command Cmdlet, you should run it as the following

Invoke-Command -ComputerName $ComputresArray -ScriptBlock { Same command as you type it on your local computer }

what is the script you'r trying to run?


Tuesday, May 4, 2010 11:01 AM

like, if I run the following command,

Invoke-Command -ComputerName $Computer -ScriptBlock { write-host "This script is running on machine: $Computer" }

I know that in the script block, the value of $Computer is null, rather than the expected value which should be the remote computer name.


Thursday, May 6, 2010 3:05 PM | 2 votes

Maybe a question for a new thread, but will

$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("write-host "This script is runnong on machine: $Computer")

be the same as:

$scriptblock = [scriptblock]::create("write-host "This script is runnong on machine: $Computer")

$m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})