![](/img/trans.png)
[英]Run python code from stdin with additional script arguments in PowerShell
[英]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.