从Python调用PowerShell脚本

发布于 2021-01-29 17:44:37

我正在尝试从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的帮助”以了解更多详细信息。

尽管事实上我很早以前确实通过键入Set-ExecutionPolicy Unrestriced管理员运行的PS终端来启用Powershell中的运行脚本(然后再做一次,只是为了确保这一事实)。powershell可执行文件与“开始”菜单中的快捷方式所指向的可执行文件相同。无论我是否以管理员身份运行PowerShell,都可以Get- ExecutionPolicy正确报告Unrestricted

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

关注者
0
被浏览
167
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    首先,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')
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看