Home > Blockchain >  Why can't I execute remote scripts using powershell (5.1)
Why can't I execute remote scripts using powershell (5.1)

Time:01-19

I have two computers on the same domain. winrm is running on both machines. Test-WSMan is running on the remote machine. I can execute invoke-command -scriptblock {dir c:\automatedtests} -computername RemoteComputername and it returns the expected result:

Directory: C:\automatedtests


Mode                LastWriteTime         Length Name                                PSComputerName

d-----        1/11/2022   5:45 PM                ErrorLog.txt                        us14-pacci04
a-----        1/13/2022  12:16 PM             18 test.ps1                            us14-pacci04

. But if I try to execute a script on that same machine (invoke-command -computername 'RemoteComputerName' -filepath 'C:\AutomatedTests\test.ps1') I get the error:

invoke-command : Cannot find path 'C:\AutomatedTests\test.ps1' because it does not exist.
At line:1 char:1
  invoke-command -session $s -filepath {C:\AutomatedTests\test.ps1}
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  CategoryInfo          : ObjectNotFound: (C:\AutomatedTests\test.ps1:String) [Invoke-Command], ItemNotFoundExcepion
  FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand

I have been googling this for days with no solution. What am I missing? It's got to be something simple that I'm missing.

Edit 1/18/22 1:18pm PT: OK - I understand now that -filepath refers to a local file. So the only way to run a script on a remote computer (with the script stored there) is to use the share?

CodePudding user response:

You can use $sess = New-PSSession... to connect to the remote machine, then Copy-Item -ToSession $sess ... to copy the file over to a folder on the remote machine, then Invoke-Command -Session $sess ... to run it on the remote machine.

(This saves you the double-hop problem of running a command on the remote machine which needs to connect out to a fileshare)

CodePudding user response:

You can invoke the script on the remote host using the call operator &:

Invoke-Command -ScriptBlock { & 'c:\automatedtests\test.ps1'} -ComputerName RemoteComputer

Or the dot sourcing operator .:

Invoke-Command -ScriptBlock { . 'c:\automatedtests\test.ps1'} -ComputerName RemoteComputer
  •  Tags:  
  • Related