Python findstr函数没有';我无法处理原始文件

Python findstr函数没有';我无法处理原始文件,python,powershell,subprocess,findstr,Python,Powershell,Subprocess,Findstr,我有一个代码,可以使用powershell使用Get-GPOReport导出域控制器的策略。但是,我不能在这个导出的HTML文件上使用findstr。唯一可行的方法是将HTML文件的扩展名改为.txt,然后将其中的所有内容复制到另一个新创建的.txt文件(例如test.txt) 只有这样,findstr函数才能工作。有人知道为什么它不能在原始文件上工作吗 import os, subprocess subprocess.Popen(["powershell","G

我有一个代码,可以使用powershell使用Get-GPOReport导出域控制器的策略。但是,我不能在这个导出的HTML文件上使用findstr。唯一可行的方法是将HTML文件的扩展名改为.txt,然后将其中的所有内容复制到另一个新创建的.txt文件(例如test.txt)

只有这样,findstr函数才能工作。有人知道为什么它不能在原始文件上工作吗

import os, subprocess

subprocess.Popen(["powershell","Get-GPOReport -Name 'Default Domain Controllers Policy' -ReportType HTML -Path 'D:\Downloads\Project\GPOReport.html'"],stdout=subprocess.PIPE)

policyCheck = subprocess.check_output([power_shell,"-Command", 'findstr /c:"Minimum password age"', "D:\Downloads\Project\GPOReport.html"]).decode('utf-8')

print(policyCheck)


# However if I copy all the content in D:\Downloads\Project\GPOReport.html to a newly created test.txt file (MANUALLY - I've tried to do it programmatically, findstr wouldn't work too) under the same directory and use:

power_shell = os.path.join(os.environ["SYSTEMROOT"], "System32","WindowsPowerShell", "v1.0", "powershell.exe")

policyCheck = subprocess.check_output([power_shell,"-Command", 'findstr /c:"Minimum password age"', "D:\Downloads\Project\test.txt"]).decode('utf-8')

print(policyCheck)

# Correct Output Will Show

我得到的是:

subprocess.CalledProcessError: Command '['C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', '-Command', 'findstr /c:"Minimum password age"', 'D:\Downloads\Project\GPOReport.html']' returned non-zero exit status 1.
预期产出:

<tr><td>Minimum password age</td><td>1 days</td></tr>
最短密码期限1天

我不是Python迷,但我认为这可能是一个编码问题。基于findstr不兼容Unicode这一事实。正如@iRon所建议的那样,
Select String
应该可以做到这一点,尽管您可能必须引用
.Line
属性才能获得您提到的预期输出。另一方面,它将返回匹配对象

我将让您将其转换为Python代码,但是
selectstring
命令应该类似于:

(Select-String -Path "D:\Downloads\Project\GPOReport.html" -Pattern "Minimum password age" -SimpleMatch).Line

如果有多个匹配项,这将返回一个字符串数组;进行匹配的线路。如果有帮助,请告诉我。

我不是Python爱好者,但我认为这可能是一个编码问题。基于findstr不兼容Unicode这一事实。正如@iRon所建议的那样,
Select String
应该可以做到这一点,尽管您可能必须引用
.Line
属性才能获得您提到的预期输出。另一方面,它将返回匹配对象

我将让您将其转换为Python代码,但是
selectstring
命令应该类似于:

(Select-String -Path "D:\Downloads\Project\GPOReport.html" -Pattern "Minimum password age" -SimpleMatch).Line

如果有多个匹配项,这将返回一个字符串数组;进行匹配的线路。让我知道这是否有帮助。

一般建议:不要使用外部遗留命令,如
findstr
,而是使用本机PowerShell cmdlet,如:将尝试一下,谢谢!一般建议:不要使用外部遗留命令,如
findstr
,而要使用本机PowerShell cmdlet,如:将尝试一下,谢谢!它似乎起作用了!非常感谢您,也感谢用户iRon。它似乎正在工作!非常感谢您,也感谢用户iRon。