Powershell 3:删除最后一行文本文件

Powershell 3: Remove last line of text file

我正在使用以下脚本遍历文件夹中的文件列表,然后它将使用正则表达式搜索包含 'T|0-9' 的字符串,它是尾部记录,将出现在每个文本文件。

$path = "D:\Test\"
$filter =  "*.txt"
$files = Get-ChildItem -path $path -filter $filter

foreach ($item in $files)

{
            $search = Get-content $path$item
            ($search)| ForEach-Object { $_ -replace 'T\|[0-9]*', '' } | Set-Content $path$item

}

这个脚本工作正常,但是,它可能需要很长时间才能遍历大文件,因此我使用了'-tail 5'参数,这样它就会从最后5行开始搜索,问题是它正在删除所有内容,只保留提要中的最后几行。

还有其他方法可以实现吗?

我尝试了我找到的另一个示例代码,但它并没有真正起作用,请有人指导我

$stream = [IO.File]::OpenWrite($path$item)
$stream.SetLength($stream.Length - 2)
$stream.Close()
$stream.Dispose()

由于 Get-Content returns 和 array,您可以使用 [-1]:

访问最后一项(最后一行)
foreach ($item in $files)
{
    $search = Get-content $item.FullName
    $search[-1] = $search[-1] -replace 'T\|[0-9]*', ''
    $search | Set-Content $item.FullName
}