我有powershell脚本,它从python GUI获取输入。脚本看起来像(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"
}
我在powershell窗口中的执行行如下:
PS dir>powershell -executionpolicy bypass -Command .\foo.ps1 "my_username" "my_password" "Computer1, Computer2" "User1, User2"
当我的密码包含'}','{','(',')',',','&',';'等特殊字符时出现问题需要在这些撇号内传递。但是当它包含像'“`这样的字符时,它会引发异常:”字符串缺少终结符:'。
我该如何解决?我使用python子进程使用该python脚本中的变量将该行输入到powershell。
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())
期待一种解决此问题的简单方法。 当我们通过提示输入特殊字符时,即来自powershell中的“读取主机”行,它可以毫无困难地接受所有内容。 反正我是否可以使用python子进程自动执行读取主机提示输入?
答案 0 :(得分:1)
尝试以列表格式发送所有cmd参数。
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())