Search code examples
powershellpowershell-remoting

Passing variables to a PoSh remote file to execute


I am trying to run a PS Remote session from Machine A to access Machine B. Both are on the same domain and Kerberos authentication is working and I can establish a PS Remote session.

I am trying to run a script from Machine A on MAchine B passing parameters to that script as follows:

$build_script_dir = Resolve-Path .
$file_to_execute = "$build_script_dir\file_to_execute.ps1"

invoke-command -ComputerName MachineB -FilePath $file_to_execute -argumentlist $Arg1,$Arg2,$Arg3,$Arg4

This doesn't seem to invoke the script. I have even tried to take the script to the remote machine and then execute it that way as follows:

$remote_file = "c:\path-to-file\remote_file.ps1"

invoke-command -ComputerName MachineB -ScriptBlock {$remote_file} -argumentlist $Arg1,$Arg2,$Arg3,$Arg4

What am I missing that is stopping the script from running? I have about 10 arguments to pass to the script and the script will manipulate IIS.

Paul


Solution

  • if the script exists only on the remote machine:

    Invoke-Command -ComputerName Server01 -scriptBlock { C:\scripts\Test.PS1 "Arguments here"}
    

    -FilePath looks for the script on local machine.

    When you specify the filepath inside -ScriptBlock, you can invoke a script residing on remote system.

    Also, if you need to pass any variables from local machine to remote script, use the -Argumentlist. But, the -ScriptBlock requires a param(). For example,

    Invoke-Command -ComputerName Server01 -scriptBlock { param($name, $age) C:\scripts\Test.PS1 -Name $name -Age $age} -ArgumentList $name,$age
    

    In the above command, $name and $age are the local variables.