0

Running into issues executing a PowerShell script from within Python.

The Python itself is simple, but it seems to be passing in \n when invoked and errors out.

['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL

This is the code in full:

import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]

print command   #<--- this is where I see the \n. 
#\n does not appear when I simply 'print script'

So I have two questions:

  1. How do I correctly store the script as a variable without writing to disk while avoiding \n?
  2. What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Numpty
  • 1,461
  • 5
  • 19
  • 28

2 Answers2

2
  1. How do I correctly store the script as a variable without writing to disk while avoiding \n?

This question is essentially a duplicate of this one. With your example it would be okay to simply remove the newlines. A safer option would be to replace them with semicolons.

script = fetch.read().replace('\n', ';')
  1. What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?

Your command must be passed as an array. Also you cannot run a sequence of PowerShell statements via the -File parameter. Use -Command instead:

rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

I believe this is happening because you are opening up PowerShell and it is automatically formatting it a specific way.

You could possibly do a for loop that goes through the command output and print without a /n.

Kody
  • 1