Skip to content Skip to sidebar Skip to footer

Running Powershell Script From Python

I'm trying to run a Powershell Script ( check below ) First remark, my Powershell script, when running with Powershell works fine, giving the expected result ( closing all open fo

Solution 1:

Here I have created my own functionto run anypowershell script with its parameters

import subprocess  # IMPORT FOR SUB PROCESS . RUN METHOD

POWERSHELL_PATH = "powershell.exe"# POWERSHELL EXE PATH
ps_script_path = "C:\\PowershellScripts\\FTP_UPLOAD.PS1"# YOUR POWERSHELL FILE PATHclassUtility:  # SHARED CLASS TO USE IN OUR PROJECT    @staticmethod    # STATIC METHOD DEFINITIONdefrun_ftp_upload_powershell_script(script_path, *params):  # SCRIPT PATH = POWERSHELL SCRIPT PATH,  PARAM = POWERSHELL SCRIPT PARAMETERS ( IF ANY )

        commandline_options = [POWERSHELL_PATH, '-ExecutionPolicy', 'Unrestricted', script_path]  # ADD POWERSHELL EXE AND EXECUTION POLICY TO COMMAND VARIABLEfor param in params:  # LOOP FOR EACH PARAMETER FROM ARRAY
            commandline_options.append("'" + param + "'")  # APPEND YOUR FOR POWERSHELL SCRIPT

        process_result = subprocess.run(commandline_options, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True)  # CALL PROCESSprint(process_result.returncode)  # PRINT RETURN CODE OF PROCESS  0 = SUCCESS, NON-ZERO = FAIL  print(process_result.stdout)      # PRINT STANDARD OUTPUT FROM POWERSHELLprint(process_result.stderr)      # PRINT STANDARD ERROR FROM POWERSHELL ( IF ANY OTHERWISE ITS NULL|NONE )if process_result.returncode == 0:  # COMPARING RESULT
            Message = "Success !"else:
            Message = "Error Occurred !"return Message  # RETURN MESSAGE

Solution 2:

You can use subprocess.run and need PIPE and shell. The following code worked for me:

import subprocess
result = subprocess.run([r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', r'C:\Users\(correct subfolders)\TEST.ps1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
print(result)

Printing the result can give you the return value like if the command was successfully executed. If you want to extract the result value, you can do,

print(result.stdout.decode('utf-8'))

Post a Comment for "Running Powershell Script From Python"