簡體   English   中英

如何以PowerShell中的參數作為管理員運行python腳本

[英]How run python script with arguments from powershell as admin

關於這個主題有各種各樣的話題,但是似乎對我的具體情況沒有幫助。 我通常不是Windows用戶,所以也許我缺少了一些東西。

我需要從單個Windows(2016)Powershell腳本運行帶有參數的一系列python腳本。 python腳本必須以管理員身份運行(因為它們需要訪問本地注冊表)。

根據該主題其他線程中的內容,我已經做到了這一點:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Unrestricted -File `"$PSCommandPath`"" -Verb RunAs; exit }


& python.exe V:Scripts\script.py --hostnames del rodney

這將以管理員身份啟動一個子外殼,但是在運行python腳本時該子外殼會失敗。 在我有機會看到錯誤消息之前,該子外殼消失了,但是Powershell事件日志指出“引擎狀態從可用更改為已停止”,我認為這是一個權限錯誤。

如果直接從管理員Powershell運行,則python腳本可以正常工作。 任何指針都非常感謝。

您的代碼正在檢查當前Powershell會話是否以管理員身份運行,如果不是,則它以管理員身份運行另一個會話。

但是,您的python代碼仍在初始Poweshell會話中運行(未以管理員身份運行)。

修改您的代碼,如下所示:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Unrestricted -command ""python.exe V:Scripts\script.py --hostnames del rodney""" -Verb RunAs
} else {
    python.exe V:Scripts\script.py --hostnames del rodney
}

這將檢查當前會話是否以管理員身份運行,它將直接運行python代碼; 如果不是,它將以管理員身份運行新的Powershell會話並在其中運行python代碼。

暫無
暫無

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

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