【问题标题】:Raw string to a Powershell script through command line通过命令行到 Powershell 脚本的原始字符串
【发布时间】:2018-08-21 07:27:04
【问题描述】:

我有一个 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"

当我的密码包含特殊字符时出现问题,例如 '}'、'{'、'('、')'、','、'&'、';'需要在这些撇号内传递。但是当它包含像'"`这样的字符时,它会抛出一个异常:"The string is Missing the terminator: '。

我该如何解决。我使用 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 中的 'read-host' 行输入,它可以毫无问题地接受所有内容。 无论如何,我可以使用 python subprocess 自动执行读取主机提示输入吗?

【问题讨论】:

    标签: python-2.7 powershell subprocess command-line-arguments rawstring


    【解决方案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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2013-05-01
      • 2016-07-24
      相关资源
      最近更新 更多