簡體   English   中英

從Python調用PowerShell腳本

[英]Invoking a PowerShell script from Python

我正在嘗試從python這樣啟動PowerShell腳本:

psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             './buildxml.ps1',
                             arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()

問題是我得到以下錯誤:

無法加載文件C:\\ Users \\ sztomi \\ workspace \\ myproject \\ buildxml.ps1,因為在此系統上禁用了腳本的執行。 請參閱“獲取有關about_signing的幫助”以了解更多詳細信息。

盡管事實上我很早以前確實在管理員運行的PS終端中通過鍵入Set-ExecutionPolicy Unrestriced啟用了Powershell中運行的腳本的事實(然后再做一次,只是為了確保)。 powershell可執行文件與開始菜單中的快捷方式所指向的可執行文件相同。 無論我是否以管理員身份運行PowerShell, Get-ExecutionPolicy正確報告Unrestricted

如何從Python正確執行PS腳本?

首先, Set-ExecutionPolicy Unrestriced是基於每個用戶和每個位(32位與64位不同)的。

其次,您可以從命令行覆蓋執行策略。

psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             '-ExecutionPolicy',
                             'Unrestricted',
                             './buildxml.ps1',
                             arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()

顯然,您可以使用以下路徑從32位PowerShell訪問64位PowerShell(感謝@eryksun):

powershell64 = os.path.join(os.environ['SystemRoot'], 
    'SysNative' if platform.architecture()[0] == '32bit' else 'System32',
    'WindowsPowerShell', 'v1.0', 'powershell.exe')

對於我們這些想知道在傳遞給powershell之后如何顯示arg1,arg2和arg3的值的人,您要做的就是:

Write-Host $args[0]
Write-Host $args[1]
Write-Host $args[2]

暫無
暫無

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

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