Photo by Claudio Schwarz | @purzlbaum on Unsplash

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 sys
source = "SOURCE_PATH"/file.txt
destination = "DESTINATION_PATH"/file.txt
output = subprocess.Popen(['powershell.exe', "Powershell_script" ,source,destination], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)print(

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"
Write-Host "File copying failed"