Executing PowerShell commands with Python 3.5
我一直在研究一个需要Python脚本通过PowerShell命令行运行的问题。 该脚本应将命令传递到命令行并保存输出。 但是,我遇到了无法识别某些命令行参数的问题。
1 2 3 4 5 6 7 8 | import subprocess try: output = subprocess.check_output\ (["Write-Output 'Hello world'"], shell=True) # (["dir"], shell=True) except subprocess.CalledProcessError as e: print(e.output) print('^Error Output^') |
如果我将当前命令与
1 2 | '"Write-Output 'Hello world'"' is not recognized as an internal or external command, operable program or batch file. |
如果仅使用
对于为什么会发生这种情况的任何见解将不胜感激。 如果相关,我不想使用任何类型的管理员特权解决方法。
我相信这是因为在Windows中,默认的Shell不是PowerShell,您可以执行Powershell命令,通过使用所需的参数执行Powershell来调用可执行文件。
例如
1 2 3 4 5 6 7 | POWERSHELL_COMMAND = r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe' subprocess.Popen([POWERSHELL_COMMAND, '-ExecutionPolicy', 'Unrestricted', 'Write-Output', 'Hello World'], stdout = subprocess.PIPE, stderr = subprocess.PIPE) |
如果powershell不在路径中,则可以使用可执行文件的完整路径
或者,如果它在路径中,请小心使用
要验证路径中是否具有Powershell,可以转到配置并进行检查,或者可以打开
从文档:
On Windows with shell=True, the COMSPEC environment variable specifies the default shell.
因此,