从Python调用PowerShell脚本

Tam*_*lei 15 python powershell

我正试图从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()
Run Code Online (Sandbox Code Playgroud)

问题是我收到以下错误:

无法加载文件C:\ Users\sztomi\workspace\myproject\buildxml.ps1,因为在此系统上禁用了脚本的执行.有关详细信息,请参阅"get-help about_signing".

尽管我很久以前通过输入Set-ExecutionPolicy Unrestriced管理员运行的PS终端(并再次确认)确实启用了在Powershell中运行脚本的事实.powershell可执行文件与开始菜单中的快捷方式指向的相同.无论我是否以管理员身份运行PowerShell,都会Get-ExecutionPolicy正确报告Unrestricted.

如何从Python正确执行PS脚本?

Jas*_*her 16

首先,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()
Run Code Online (Sandbox Code Playgroud)

显然,您可以使用此路径从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')
Run Code Online (Sandbox Code Playgroud)

  • 哇,太好了,谢谢!实际上,我只是发现问题是由于臭名昭着的Windows 7 x64文件系统重定向造成的.(我在x64版本中有Unrestricted策略,但在x86中没有,并且python没有重定向到它). (2认同)
  • 使用虚拟"SysNative"目录从32位WOW64程序运行本机64位系统可执行文件.另外,不要硬编码系统根目录"C:\ Windows"; 并不总是安装Windows的地方.我会使用`powershell64 = os.path.join(os.environ ['SystemRoot'],'SysNative'如果platform.architecture()[0] =='32位'别的'System32','WindowsPowerShell','v1. 0','powershell.exe')`. (2认同)