0

Trying to run a PowerShell script using WinRM

# $cred is valid and works for common PowerShell cmdlets

script = """
Start-Process ping.exe -Credential $cred -NoNewWindow -Wait -RedirectStandardOutput out.txt
Get-Content out.txt
"""
session = winrm.Session(host, auth=(user,passwd), transport="credssp')
result = s.run_ps(script)

If -Credentials is not used, the output is returned.

Otherwise, this creates an empty out.txt file. How do I redirect the output to out.txt/stdout?

Manas
  • 113
  • 1
  • 7

1 Answers1

1

You can not do this with PowerShell natively. It is a Windows proper security boundary. PowerShell will always run in the context of the user who ran the code.

To do this, you need to use an external tool, like MS SysInternals PSExec...

# Example:
# Using PsExec to Run Command on Remote Computer
psexec \\RemotePCName [-u username[-p password]] command [arguments]

psexec \\lon-srv01 powershell -ExecutionPolicy RemoteSigned -command "'{0:N2}' -f ((gci C:\PS | measure Length -Sum).Sum/1MB)"

... or use a scheduled task to run code at logon, or some other point in the day.

Don't use Credssp unless you have no other choice.

Accidental Sabotage: Beware of CredSSP: https://www.powershellmagazine.com/2014/03/06/accidental-sabotage-beware-of-credssp/

PowerShell redirection is still tied to the user session. Yet, take a look at this Stackoverflow Q&A:

Redirect STDOUT\STDERR to current shell from win32_process create on remote computer

postanote
  • 15,138
  • 2
  • 14
  • 25
  • Updated the title to reflect that the issue is capturing the cmd's output. Even when using psexec, I get command.exe exited with error code 0. The output is not redirected to text file. – Manas May 06 '20 at 18:50