【问题标题】:Fetch PowerShell script from GitHub and execute it从 GitHub 获取 PowerShell 脚本并执行它
【发布时间】:2017-03-21 03:02:53
【问题描述】:

在 Python 中执行 PowerShell 脚本时遇到问题。

Python 本身很简单,但它似乎在调用时传入了\n 并出现错误。

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

这是完整的代码:

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'

所以我有两个问题:

  1. 如何在避免\n的同时正确地将脚本存储为变量而不写入磁盘?
  2. 从 Python 中调用 PowerShell 以运行存储在 $script 中的脚本的正确方法是什么?

【问题讨论】:

    标签: python powershell urllib2


    【解决方案1】:
    1. 如何在避免\n的同时正确地将脚本存储为变量而不写入磁盘?

    这个问题本质上是this one 的重复。使用您的示例,只需删除换行符即可。更安全的选择是将它们替换为分号。

    script = fetch.read().replace('\n', ';')
    
    1. 从 Python 中调用 PowerShell 以运行存储在 $script 中的脚本的正确方法是什么?

    您的命令必须作为数组传递。此外,您不能通过 -File 参数运行一系列 PowerShell 语句。请改用-Command

    rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
    

    【讨论】:

      【解决方案2】:

      我相信这是因为您正在打开 PowerShell,它会自动以特定方式对其进行格式化。

      您可以执行一个 for 循环,该循环遍历命令输出并在没有 /n 的情况下打印。

      【讨论】:

        猜你喜欢
        • 2014-01-06
        • 2011-07-16
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多