After a slow start, there is now a large availability of powershell cmdlets to control most things in Windows. Whats more, powershell cmdlets are sometimes the only programmatic way to control some software. This means at some point you are likely to need to use cmdlets from Python. Until there is a native way of doing this with a Python module the easiest way is with subprocess as done previously for shell commands.
Whole Powershell scripts, not just single commands, can be ran with the powershell.exe command. There are three command line options that will be useful, -NoLogo removes the banner at startup, -ExecutionPolicy if set to bypass should run the script regardless to what the current execution policy is without changing the settings and -File to specify the script to run.
So just save the command(s) to execute into a temporary file and then call powershell.exe with the above options and the file name of the temp file to run. One oddity is powershell.exe requires the file to have a .ps1 extension or it will refuse to run it. You can do this by passing suffix=’.ps1′ into NamedTemporaryFile.
Putting all this together gives the following
import subprocess, tempfile, sys, os def posh(command): commandline = ['powershell.exe',' -NoLogo','-ExecutionPolicy','Bypass','-File'] with tempfile.NamedTemporaryFile(suffix=".ps1",delete=False) as f: f.write(command) commandline.append(f.name) try: result = subprocess.check_output(commandline) exitcode = 0 except subprocess.CalledProcessError as err: result = err.output exitcode = err.returncode os.unlink(f.name) return exitcode , result retcode, retval = posh("Write-Host 'Hello Python from PowerShell'\nexit 1") print("Exit code: %d\nReturned: %s" % (retcode, retval))
Note that to get the output in the case of an error you need to get it from error object.