PowerShell – Running a Program Remotely With Arguments

I was having trouble with getting a certain program to run remotely from a PowerShell script, I just couldn’t get it to run using Start-Process, Invoke-Command, or using the old WMI create method. Each of them was giving me its own headache, and it seemed like I could sort of get one to work, but each time I got a part working another fell apart. I was able to get the program running locally using Start-Process, so I decided that this was going to be my savior but I needed to get it running remotely.

I ended up using a combination of Invoke-Command and Start-Process to do the job. But this has its own ‘gotchas’ (I hate that word) that need to be taken in to account. Invoke-Command requires you to pass some form of a script block, and local variables don’t work inside of it. I tried a couple of ways of getting those working, including declaring them in the script block itself. This kind of worked, but I couldn’t turn it in to a function easily. Finally I caught this post: https://blogs.msdn.microsoft.com/powershell/2009/12/29/how-to-pass-arguments-for-remote-commands/

This pointed me to the magic of $args. Basically your local variables can be bound to the $args variable and easily passed to your script block.

Anyway, here’s the code of my working script block:

$PSSession = New-PSSession -ComputerName $Server
Invoke-Command -Session $PSSession -ScriptBlock {
$param1 = $args[0]
$param2 = $args[1]
$Client = $param1 + "_" + $param2

$Arguments = @"
-PublishItem -a "$Client" -ItemPath "D:\$param1\$param2\executable1.EXE" -StartDirectory "D:\$param1\$param2\" -r "/option"
Start-Process -FilePath "C:\Program Files\Some Company\Programs\executable2.exe" -ArgumentList $Arguments
}$args "Test", "defiantOwl"

All you need to do is to put $args with an index value when instantiating your variable in the script block, then pass these variables (separated by commas) at the end of your script block.

As always, please leave a comment if you have a question and I’ll do my best to respond.


107 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *