Skip to main content
 首页 » 编程设计

python之'Select-Object' 不是内部或外部命令,也不是可运行的程序或批处理文件

2024年10月24日15lvdongjie

我想通过 powershell 的 Enable-WindowsOptionalFeature 启用 IIS。有一个 python 程序只有一行代码:

os.system('powershell.exe Enable-WindowsOptionalFeature -Online -FeatureName $(Get-WindowsOptionalFeature -Online | Where { $_.FeatureName -Like "IIS-*"} | Select-Object -ExpandProperty FeatureName)') 

当我运行 python 程序时,它说 'Select-Object' 不是内部或外部命令,也不是可运行的程序或批处理文件。

我搜索了很多方法,但是没有人能解决这个问题,有人可以帮我解决这个问题吗?谢谢。

请您参考如下方法:

我想 os.system 调用正在使用 cmd.exe,它会在您的参数到达 powershell.exe 之前对其进行处理。管道之前的所有内容都传递给 powershell.exe,之后的所有内容都传递给 cmd.exe 程序。没有Select-Object程序。

使用 Python 的 subprocess module根据 recommendations in the system function's documentation 而不是 os.system :

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

您还可以对命令进行 base-64 编码并将其传递给 PowerShell 的 -EncodedCommand 属性。

cmd = base64.b64encode( "Enable-WindowsOptionalFeature -Online -FeatureName $(Get-WindowsOptionalFeature -Online | Where { $_.FeatureName -Like "IIS-*"} | Select-Object -ExpandProperty FeatureName)'" 
os.system("powershell.exe -EncodedCommand " + cmd)