0

Powershell script executes commandline on local machine

$j = "remote_machine"

$comp = "\\"+$j

$command = 'D:\PSTools\PsExec.exe $comp -u Administrator -p plaintextpassword -accepteula powershell.exe c:\share\script.ps1'

Invoke-Expression "& $command"

This works, but it outputs following

PsExec.exe : At line:1 char:1 + & D:\PSTools\PsExec.exe $comp -u Administrator -p plaintextpassword -accepteula powersh ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError PsExec v2.0 - Execute processes remotely Copyright (C) 2001-2013 Mark Russinovich Sysinternals - www.sysinternals.com Connecting to remote_machine...Starting PSEXESVC service on remote_machine...Connecting with PsExec service on remote_machine...Starting powershell.exe on remote_machine... powershell.exe exited on remote_machine with error code 0.

How to fix?

Glowie
  • 2,271
  • 21
  • 60
  • 104
  • PSExec likes to look like it is throwing errors because of how it outputs text to stderr (error output stream) instead of stdout (standard output stream). Is this that, or is it actually throwing an error and failing to do what it is supposed to? – TheMadTechnician Sep 09 '14 at 15:09
  • One thing is that you need to use double-quote (`"`) instead of single quotes (`'`) in `$command`. String interpolation only occurs within double-quoted strings. Also, I think you can just use `& $command`. `Invoke-Expression` is superfluous. – Mike Zboray Sep 09 '14 at 16:29

1 Answers1

1

After re-reading your question I see that this is the standard PSExec vs PowerShell issue that has been seen and discussed before. This is due to the fact that PSExec outputs its header lines to the stderr (Standard Error) stream for some of its text. The execution works fine, and it does show an exit code of 0 indicating that there is not actually an error.

This issue is only evident in PowerShell ISE, not the standard PowerShell console (unless you redirect StdErr to StdOut with PSExec <command & args> 2>&1 or something similar). To work around this, if you are going to run the script in the ISE, you can use Start-Process's -RedirectStandardError argument, or redirect StdErr through other means.

TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56