Running Powershell script from python using subprocess

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"




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Do I Need an Application Performance Monitor (APM) Tool?

The Functor class in Haskell, what is it?

Developing software to solve the problem of counting growing plants

Η επένδυσή μας στο Factor[e] Ventures — Autodesk Foundation

Why you shouldn't Use IDE?

Getting Hands-on with WinAppDriver Test Automation Framework

Configuring ELK stack in winodws.

5 Reasons Why Hackathons Make Perfect Sense

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


More from Medium

Python selenium | login with cookies

Python Sys Module All Notes

DelayQueue in Python

Loading CSV Contents in IBM Cloud Object Storage into Pandas DataFrames using Python