Skip to content

Instantly share code, notes, and snippets.

@erlingpaulsen
Last active February 1, 2022 11:15
Show Gist options
  • Save erlingpaulsen/011fd099bc1b4949be1f1b3c772b1847 to your computer and use it in GitHub Desktop.
Save erlingpaulsen/011fd099bc1b4949be1f1b3c772b1847 to your computer and use it in GitHub Desktop.
Running PowerShell commands in Python - Three simple examples
import subprocess
import datetime
# PARAMETERS
powershell_exe = 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe'
def custom_print(severity, message):
print('{0} - [{1}] - {2}'.format(datetime.datetime.now(), severity, message))
def createFolder(path, name):
result = subprocess.run('{0} New-Item -Path "{1}" -Name "{2}" -ItemType "directory"'.format(powershell_exe, path, name), shell=True, capture_output=True, text=True)
if result.returncode != 0:
custom_print('ERROR', 'Could not create directory \'{0}\' in {1}. Return code: {2}. Error message: {3}'.format(name, path, result.returncode, result.stderr))
return result.returncode
def listFiles(directory, extension=None):
if extension:
result = subprocess.run('{0} Get-ChildItem "{1}" -Name -File -Include *.{2}'.format(powershell_exe, directory, extension), shell=True, capture_output=True, text=True)
else:
result = subprocess.run('{0} Get-ChildItem "{1}" -Name -File'.format(powershell_exe, directory), shell=True, capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip().split('\n')
else:
custom_print('ERROR', 'Could not list files in directory {0}. Return code: {1}. Error message: {2}'.format(directory, result.returncode, result.stderr))
return []
def listDirectories(directory):
result = subprocess.run('{0} Get-ChildItem "{1}" -Name -Directory'.format(powershell_exe, directory), shell=True, capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip().split('\n')
else:
custom_print('ERROR', 'Could not list directories in directory {0}. Return code: {1}. Error message: {2}'.format(directory, result.returncode, result.stderr))
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment