首页 > 解决方案 > findstr 函数不适用于原始文件

问题描述

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

标签: pythonpowershellsubprocessfindstr

解决方案


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

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

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

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


推荐阅读