How to use Script Parameters with Invoke-Command

Nanne14 20 Reputation points
2023-11-30T10:25:41.4233333+00:00

I'm currently facing a challenge while using remote PowerShell over SSH to execute a script on a Windows machine and pass parameters.

Locally, I run the script with parameters using this command:

.\Update-PasswordArchive.ps1 -LocalUserName Administrator

However, when attempting to run the script remotely using Invoke-Command, I encounter difficulties passing the -LocalUserName parameter. Here's the remote command I use: *

Invoke-Command -HostName '192.168.1.100:54823' -FilePath C:\_scripts\Update-PasswordArchive.ps1

The problem is because, with Invoke-Command, I can't directly pass parameters for the script as I normally would. If I append the parameters after the script, it produces an error, as they are interpreted by the Invoke-Command itself rather than being passed to the script.

Is there a recommended solution or workaround for passing parameters when using Invoke-Command over SSH?

*(Don't get confused by the hostname, this is the IP of a VyOS Gateway and by the rule configured to port 54823 it useses NAT to forward to the desired maschine behind it) - So I assume there is no other way to remote PowerShell as SSH. I need a fix port and I have to use the IP:Port combination for the connection.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2023-11-30T13:48:47.5366667+00:00

    Use the ArgumentList switch for positional parameters.

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-5.1

    Or use a script block.

    Invoke-Command -ComputerName '192.168.1.100:54823' -ScriptBlock {          C:\_scripts\Update-PasswordArchive.ps1 -LocalUserName Administrator
    }
    

    Or..

    $acct = "admin"
    Invoke-Command -ComputerName '192.168.1.100:54823' -ScriptBlock {    C:\_scripts\Update-PasswordArchive.ps1 -LocalUserName $using:acct
    }
    
    
    

    See the answer from RobG.

    https://stackoverflow.com/questions/4225748/how-do-i-pass-named-parameters-with-invoke-command

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.