PowerShell – Passing Parameters as Variables using Remote Management and Invoke-Command


Recently I had a need to write a PowerShell script that could accept a set of parameters at script launch, and pass those parameters to an inline scriptblock to allow the input parameters to act as variables in a set of commands against a remote server.  Looking at the documentation for the Invoke-Command cmdlet I saw that there was a parameter named ArgumentList, and looking at its description it seemed like the perfect fit for what I was looking to do.  The description for ArgumentList states that it, “Supplies the values of local variables in the command. The variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with variables in the order that they are listed.”

Looking at the syntax and examples for the ArgumentList parameter, I was unable to find any details for using it with a set of input parameters, so once I was able to pull something together that worked I figured it would be worth to share a full example of this functionality in action.

Example script basicremoting.ps1

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
#.\BasicRemoting.ps1 -remoteserver LAB01 -eventloginput Application -numinput 10
Param
(
  [string]$remoteserver,
  [string]$eventloginput,
  [string]$numinput
)

$ScriptBlockContent =
{
$eventlog = $args[0]
$num = $args[1]
get-eventlog -logname $eventlog -newest $num
}

Invoke-Command -Computer $remoteserver -ScriptBlock $ScriptBlockContent -ArgumentList $eventloginput, $numinput
#End

Comments (5)

  1. marcoolinho says:

    very helpfull.

  2. Zoltan Erszenyi says:

    Thanks Ralph, very neat and helpful. Exactly what I needed.

  3. JRPritchard says:

    Hi Ralph, to say ArgumentList is misleading would be an understatement 😀
    It makes working with these embedded sessions a real pain 🙁
    However, thank you for your nice and simple, but very clear example!

  4. Anderson says:

    Hi Ralph, thanks for your post. I was having problems with Invoke-command for almost three weeks and finally with your recommendation I could get my problem of passing parameters sorted. I really appreciate your help. God bless you.

  5. A.D. Ryan says:

    Couldn’t this work as well?

    Param
    (
    [string]$remoteserver,
    [string]$eventloginput,
    [string]$numinput
    )

    $ScriptBlockContent =
    {
    param ($eventloginput, $numinput)
    $eventlog = $eventloginput
    $num = $numinput
    get-eventlog -logname $eventlog -newest $num
    }

    Invoke-Command -Computer $remoteserver -ScriptBlock $ScriptBlockContent -ArgumentList $eventloginput, $numinput
    #End

Skip to main content