Running Powershell script from python using subprocess
Jan 29, 2021
Recently I had a requirement to run a PowerShell script from python and also pass parameters to the script.
I also want to capture the output from the PowerShell script and use it in python script. So thought of sharing it here.
Python Script
This python script runs the PowerShell script using subprocess and we are capturing the output from PowerShell using stdout, to capture error output you can use stderr
import subprocess
import syssource = "SOURCE_PATH"/file.txt
destination = "DESTINATION_PATH"/file.txtoutput = subprocess.Popen(['powershell.exe', "Powershell_script" ,source,destination], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)print(output.stdout.read().decode().strip())
Powershell Script
This script you can use to copy a file from one folder to another and also to copy files among servers.
$sourcefile = $args[0]
$destfile = $args[1]Copy-Item -Path $sourcefile -Destination $destfileif((Test-Path -Path $dest)){
Write-Host "File copied successfully"
}
else{
Write-Host "File copying failed"
}