查找功能对原始文件不起作用



我有一个代码,可以使用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:DownloadsProjectGPOReport.html'"],stdout=subprocess.PIPE)
policyCheck = subprocess.check_output([power_shell,"-Command", 'findstr /c:"Minimum password age"', "D:DownloadsProjectGPOReport.html"]).decode('utf-8')
print(policyCheck)

# However if I copy all the content in D:DownloadsProjectGPOReport.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:DownloadsProjecttest.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:DownloadsProjectGPOReport.html']' returned non-zero exit status 1.

预期输出:

<tr><td>Minimum password age</td><td>1 days</td></tr>

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

我会把它转置到 Python 代码中,但Select-String命令应该看起来像这样:

(Select-String -Path "D:DownloadsProjectGPOReport.html" -Pattern "Minimum password age" -SimpleMatch).Line

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

最新更新