findstr 函数不适用于原始文件

findstr function doesn't work on original file

我有一个代码可以使用 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>

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

我会留给你将其转换为 Python 代码,但是 Select-String 命令应该类似于:

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

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