Skip to content Skip to sidebar Skip to footer

Python Execute Powershell Command

I am try to execute a PowerShell command to get the memory usage and get the result. import subprocess output = subprocess.call(['powershell.exe', 'Get-Counter -Counter '+''\memory

Solution 1:

You need to do:

try:
   output = subprocess.check_output(
              ["powershell.exe", "Get-Counter", 
               "-Counter "+r'"\memory\available mbytes"',
               "-MaxSamples 10", "-SampleInterval 1"], 
              shell=True)
except subprocess.CalledProcessError, e:
    print"subproces CalledProcessError.output = " + e.output
print output

Notice True rather than TRUE supplying the "powershell.exe" to check_output and the r before strings with \ in.

But I would strongly recommend using psutil instead of trying to get and parse PowerShell results:

In [4]: import psutil

In [5]: psutil.virtual_memory()
Out[5]: svmem(total=17087684608L, available=8599142400L, percent=49.7, used=8488542208L, free=8599142400L)

In [6]: psutil.swap_memory()
Out[6]: sswap(total=38059204608L, used=14400655360L, free=23658549248L, percent=37.8, sin=0, sout=0)

Solution 2:

Same example as above but for Python 3:

try:
   output = subprocess.check_output(
              ["powershell.exe", "Get-Counter", 
               "-Counter "+r'"\memory\available mbytes"',
               "-MaxSamples 10", "-SampleInterval 1"], 
              shell=True)
except subprocess.CalledProcessError as e:
    print ("subproces CalledProcessError.output =", e.output)
print (output.decode())

Post a Comment for "Python Execute Powershell Command"