首页 > 解决方案 > Powershell:Get-Content 的 ForEach 行读取是否返回 EOF ..?

问题描述

读取任意大小的随机 HTML 输入文件我限制读取最多 1000 行或结束 /html 标记。工作正常。

问题出在小文件和 /html 标签丢失时。我想知道什么时候结束。

问题:是否有某种类型的 EOF 属性……?

$fileContents = (Get-Content -LiteralPath $filePath -totalcount 999)
ForEach ($line in $fileContents){
        $LineNo = $LineNo +1;
        if ((($line.ToLower().StartsWith("</html>"))) -or ($LineNo -gt 999) -or ??? END_OF_$fileContents ???)
            {
                # Do the rest of the processing in here...
            }
        }

几天后,这是我处理这个问题的最终代码(向右滚动);

$fileContents = (Get-Content -LiteralPath $filePath -totalcount 999)
ForEach ($line in $fileContents){
        $LineNo = $LineNo +1;
        if ((($line.ToLower().StartsWith("</html>"))) -or ($LineNo -gt 500) -or ($LineNo -ge $fileContents.Count))
            {
                # Do the rest of the processing in here...
            }
        }

这样做的想法是“摆脱”处理大量 html 文件,但仍然能够处理少量文件,即使它们的格式不正确(在电子邮件文件中很常见)。

标签: powershell

解决方案


无需额外的 EOF 文件检查。我们将用于Get-Content处理 EOF 检查以及行数(999 行)检查。

然后我们可以使用正则表达式来解析文件以找到关闭的 HTML 标记和行号。

$fileContents = (Get-Content -LiteralPath $filePath -TotalCount 999)

$result = $fileContents | Select-String '<\/html>'

if($result -ne $null -or $fileContents.Count -eq 999)
{
    # Hit Close HTML Tag or file is bigger than 1000 lines

    Write-Host "Hit close tag at line: $($result.LineNumber) or EOF"

    # Do the rest of the processing in here...
}

推荐阅读