BANUPRAKASH MUNNANGI
BANUPRAKASH MUNNANGI

Reputation: 63

Raw string to a Powershell script through command line

I have powershell script which takes input from a python GUI. And the script looks like (foo.ps1):

#.\foo.ps1
[String]$UserName = $args[0]
[String]$Password = $args[1]
[String[]] $ComputerName = $args[2]
[String[]] $Users = $args[3]
Write-Output "Username is $UserName"
Write-Output "Password is $Password"
foreach ($Computer in $ComputerName) { 
   Write-Output "Computer is $Computer"
}   

foreach ($User in $Users) { 
   Write-Output "Users is $User"
}

And my execution line in powershell window looks like:

PS dir>powershell -executionpolicy bypass -Command .\foo.ps1 "my_username" "my_password" "Computer1, Computer2" "User1, User2"

Problem arises when my password has special characters like '}', '{','(', ')', ',', '&', ';' need to be passed within these apostrophes. But when it contains characters like ' " `, it throws an exception: "The string is Missing the terminator: '.

How do I solve it. I use python subprocess to input that line to powershell using variables from that python script.

import subprocess
process = subprocess.Popen(['powershell.exe',"""powershell -executionpolicy bypass -File Foo.ps1 "username" "password" "computer1,computer2" "user1,user2" """], stdin=subprocess.PIPE,stdout=subprocess.PIPE)  
print(process.communicate())

Expecting a simple way to address this issue. When we enter the special characters through prompt, that is from 'read-host' line in powershell, it accepts everything without any trouble. Is there anyway that I could automate that read-host prompt input using python subprocess ?

Upvotes: 0

Views: 1801

Answers (1)

Rakesh
Rakesh

Reputation: 82785

Try sending all the cmd arguments in a list format.

import subprocess
process = subprocess.Popen("""powershell.exe powershell -executionpolicy bypass -File Foo.ps1 "username" "password" "computer1,computer2" "user1,user2" """.split(), stdin=subprocess.PIPE,stdout=subprocess.PIPE)  
print(process.communicate())

Upvotes: 1

Related Questions