Skip to content

Instantly share code, notes, and snippets.

@charudatta10
Forked from kapb14/run_powershell_cmdlet.py
Created January 29, 2023 18:33
Show Gist options
  • Save charudatta10/6e8740567e6096c80b898c32ae360617 to your computer and use it in GitHub Desktop.
Save charudatta10/6e8740567e6096c80b898c32ae360617 to your computer and use it in GitHub Desktop.
Run PowerShell commandlet or .ps1 file with parameters from python (2.7) script
#-*- coding: utf-8 -*- .
import subprocess, os, sys, json
MY_PROCESS = "chrome"
print("MY_PROCESS: %s" % MY_PROCESS)
p = subprocess.Popen([
"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",
"-ExecutionPolicy", "Bypass",
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
"& {&'Get-Process' -Name " + MY_PROCESS + " | Select-Object Product, Path, Name | ConvertTo-Json}"
], stdout=subprocess.PIPE, shell=True)
(result, err) = p.communicate()
print("result type: %s" % type(result))
python_obj = json.loads(result)
out = python_obj[0]['Product']
print("Output: %s" % out)
#-*- coding: utf-8 -*- .
import subprocess, os, sys, json
MY_PROCESS = "chrome"
print("MY_PROCESS: %s" % MY_PROCESS)
SCRIPT_FOLDER = os.path.dirname(sys.argv[0])
print("SCRIPT_FOLDER: %s" % SCRIPT_FOLDER)
p = subprocess.Popen([
"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",
"-File", SCRIPT_FOLDER + "\\test.ps1",
"-ProcessName", MY_PROCESS
], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(result, err) = p.communicate()
print("result type: %s" % type(result))
python_obj = json.loads(result)
out = python_obj
print("Output: %s" % out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment