2

I am calling a Powershell script within a Python script using Python's subprocess Popen. The Powershell script requires two input parameters: -FilePath and -S3Key. It uploads a file to AWS S3 server. If I pass in hard coded strings, the script works.

os.Popen([r'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath \"C:\TEMP\test.txt\" -S3Key \"mytrialtest/test.txt\"'])

However, if I try to pass in Python string variable, the Powershell script errors out saying it can not find the file specified by the filename variable.

filename  = 'C:\TEMP\test.txt'
uploadkey = 'mytrialtest/test.txt'

os.Popen([r'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath \"filename\" -S3Key \"uploadkey\"'])

Any help would be greatly appreciated. Thanks.

3
  • Try defining filename = '"' + r"C:\TEMP\test.txt" + '"'. Do the same thing for uploadkey. Commented Oct 19, 2013 at 0:31
  • I figured out what the issue is. Here is the solution: Commented Oct 19, 2013 at 2:21
  • Thanks David. Here is a solution I found: filename = "C:\TEMP\test.txt" uploadkey = "mytrialtest/test.txt" os.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe','-ExecutionPolicy','RemoteSigned','./Upload.ps1 -FilePath ',filename,'-S3Key ',uploadkey]) Commented Oct 19, 2013 at 2:29

1 Answer 1

2

I know, it's an old question, so this is for those who find this question via google:

The solution mentioned in comment has some risks (string injection) and might not work if there are special characters involved. Better:

import subprocess
filename = r'C:\TEMP\test.txt'
uploadkey = 'mytrialtest/test.txt'
subprocess.Popen(['powershell',"-ExecutionPolicy","RemoteSig‌​ned","-File", './Upload.ps1', '-FilePath:', filename , '-S3Key:', uploadkey])

Notice the : appended to the parameter names - in most cases it will also work without the :, but if the value starts with a dash, it will fail without the :.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.