簡體   English   中英

從GitHub獲取PowerShell腳本並執行

[英]Fetch PowerShell script from GitHub and execute it

在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存儲的$script
  1. 如何避免將\\n正確地將腳本存儲為變量而不寫入磁盤?

這個問題本質上是一個重復的這一個 以您的示例為例,只需刪除換行符就可以了。 一個更安全的選擇是用分號代替它們。

script = fetch.read().replace('\n', ';')
  1. 從Python內部調用PowerShell的正確方法是什么,以便它將運行$script存儲的$script

您的命令必須作為數組傳遞。 同樣,您無法通過-File參數運行一系列PowerShell語句。 使用-Command代替:

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

我相信這是因為您正在打開PowerShell,並且它會自動以特定方式對其進行格式化。

您可以做一個for循環,遍歷命令輸出並打印不帶/ n的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM