Home > Software design >  Capturing output from Powershell command and saving it in a variable
Capturing output from Powershell command and saving it in a variable

Time:09-03

I keep trying to run this piece of code but everytime I print, it seems to net me nothing in regards to what I see with my output.

p = subprocess.run(["powershell.exe", "C://Users//xxxxx//Documents//betterNetstatOut.ps1"], shell=True, capture_output=True, text=True)

output = p.stdout
print(output)

My PowerShell command is a very basic println at this point:

Write-Output 'Hello world'

but running print on my out seems to return an empty string. I also tried running subprocess.Popen() and subprocess.call() and they all seem to return an empty string instead of 'Hello World'. Eventually, I would like to parse many lines and move them to a dataframe but I am stuck on this one line first.

CodePudding user response:

Your PowerShell command likely produced only stderr output, which is why you saw no output given that you only printed p.stdout - also printing p.stderr would surface any stderr output (which typically contains error messages).

Assuming your script file path is correct, the likeliest explanation for receiving only stderr output is that your effective PowerShell execution policy prevents execution of scripts (.ps1 files), which you can bypass with -ExecutionPolicy Bypass in a call to the Windows PowerShell CLI, powershell.exe.

Additionally:

  • There's no need for double slashes (//) in your script path; while it still works, / is sufficient.

  • It's better to use the -File parameter rather than -Command (which is implied) for invoking scripts via the PowerShell CLI - see this answer for more information.

  • For a predictably execution environment and to avoid unnecessary overhead from loading profiles, using -NoProfile is advisable.

  • You don't need shell=True, which, due to calling via cmd.exe, only slows your command down.

To put it all together:

import subprocess

p = subprocess.run(
     ["powershell.exe", 
      "-NoProfile", 
      "-ExecutionPolicy", "Bypass", 
      "-File", "C:/Users/xxxxx/Documents/betterNetstatOut.ps1"], 
     capture_output=True, text=True
    )

print('--- stdout --')
print(p.stdout)
print('--- stderr --')
print(p.stderr)

CodePudding user response:

import subprocess

p = subprocess.run(["powershell.exe", "powershell -ExecutionPolicy Bypass -File", "C://Users//xxxxx//Documents//betterNetstatOut.ps1"], shell=True, capture_output=True, text=True)
print(p.stdout)
  • Related