Forum Discussion
John_Dodo
Oct 17, 2022Brass Contributor
Replace psexec with native powershell commands
Hello,
we have a remotely located ($remoteserver1) script that we want to run on the said remote computer ($remoteserver1) from a "controler" server (via a scheduled task).
As of today in a CMD file (located in our controler server) we have something like this :
%dir_command%\psexec.exe "\\servername" -accepteula powershell "C:\_Scripts\Pools_Scripts\myscript.ps1" "param1" "param2" "param3" "param4"
For the moment I want to replace this cmd by a ps script as a first step.
I have tried to use the call operator &, invoke-expression, invoke-command etc but nothing works.
What would be the correct method for executing a remote script on a remote computer (knowing that the script is local to the remote server) ?
As a secondary step I will probable try to run a "locally" (centralized smb share) stored script to the remote computer. But I can't go straight to this step. However if you already have recommandations for doing this I would be interested.
thank you for your help.
- John_DodoBrass ContributorI think I found the solution myself. I simply had to replace the " " by { } in the $command var.
Though I still have an issue of the nested variables not beeing interpreted.
$command = {C:\_Scripts\Pools_Scripts\myscript.ps1" "param1" "$param2" "param3" "param4" }
Invoke-Command -ComputerName $remoteserver1 -ScriptBlock $command
For my test I wrote $param2 value and it's working. If I leave $param2 in $command it is not interpreted.- John_DodoBrass ContributorSo apparently I must use $using:param2
$command = {C:\_Scripts\Pools_Scripts\myscript.ps1" "param1" "$using:param2" "param3" "param4" }
Invoke-Command -ComputerName $remoteserver1 -ScriptBlock $command
It seemd to work now.
If anyone can validate this 🙂
thank you- LainRobertsonSilver Contributor
It's odd that using the $Using scope modifier is the resolution, however, without the full scripts (from the host doing the remoting as well as the script being run on the remote host) it's too hard to say why that's needed - other than it speaks to the likelihood of a variable with the same name existing in a higher-priority scope.
Setting that aside, you'd normally go about this using -ArgumentList in the Invoke-Command and then using param() definitions within the script block to name those parameters.
Here's a basic example.
$Param1 = "Foo"; $Param2 = "Chew"; $Param3 = "Bless"; $Param4 = "You"; Invoke-Command -ComputerName "someRemoteComputer.yourdomain.com" -ArgumentList $Param1, $Param2, $Param3, $Param4 -ScriptBlock { param($LocalParam1); param($LocalParam2); param($LocalParam3); param($LocalParam4); .\MyScript.ps1 $LocalParam1 $LocalParam2 $LocalParam3 $LocalParam4; }
Still, so long as what you've got is working, the example above is nothing more than general information on passing parameters with Invoke-Command.
Cheers,
Lain