如何在PowerShell中删除命令输出的最后一行?
问题:在PowerShell中移除命令输出的最后一行(格式为“[+] Found x hits”)
需求说明
需要移除PowerShell中某命令输出的最后一行,该行固定格式为[+] Found x hits(x为动态变化的数字)。
命令输出示例
[{"Event":{"EventData":{"CommandLine":"nslookup test2.com","MandatoryLabel":"S-1-16-12288","NewProcessId":"0x2094","NewProcessName":"C:\\Windows\\System32\\nslookup.exe","ParentProcessName":"C:\\Windows\\System32\\cmd.exe","ProcessId":"0x868","SubjectDomainName":"RM-PC","SubjectLogonId":"0x1ddc2c","SubjectUserName":"richa","SubjectUserSid":"S-1-5-21-1405040689-326705664-3657760936-1001","TargetDomainName":"-","TargetLogonId":"0x0","TargetUserName":"-","TargetUserSid":"S-1-0-0","TokenElevationType":"%%1937"},"System":{"Channel":"Security","Computer":"RM-PC","Correlation":null,"EventID":4688,"EventRecordID":20413251,"Execution_attributes":{"ProcessID":4,"ThreadID":7320},"Keywords":"0x8020000000000000","Level":0,"Opcode":0,"Provider_attributes":{"Guid":"54849625-5478-4994-A5BA-3E3B0328C30D","Name":"Microsoft-Windows-Security-Auditing"},"Security":null,"Task":13312,"TimeCreated_attributes":{"SystemTime":"2022-10-12T12:11:17.996728Z"},"Version":2}},"Event_attributes":{"xmlns":"http://schemas.microsoft.com/win/2004/08/events/event"}}] [+] Found 2 hits
尝试的无效代码
$linecounter = 0 $output=\.\command.exe while($linecounter -le 1) { foreach ($line in $output){ $linecounter=$linecounter+1 Write-Host $line } }
解决方案
你写的代码逻辑完全没起到过滤最后一行的作用,while和foreach的嵌套方式不对。下面是几种简洁有效的解决方法:
方法1:直接取除最后一行外的所有内容
利用PowerShell数组索引特性,直接获取从第一行到倒数第二行的内容:
$output = .\command.exe $output[0..($output.Count - 2)] | Write-Host
方法2:正则匹配过滤目标行
如果最后一行格式固定是[+] Found x hits,用正则表达式直接过滤掉该行,这个方法更通用,哪怕目标行位置变化也能生效:
.\command.exe | Where-Object { $_ -notmatch '^\[\+\] Found \d+ hits$' }
方法3:跳过最后一行(PowerShell 5.1+支持)
用Select-Object -SkipLast 1直接跳过输出的最后一行,适合不需要额外处理的场景:
.\command.exe | Select-Object -SkipLast 1
补充说明
- 方法1适合确定最后一行就是目标行的场景;
- 方法2优先级最高,只要行格式匹配就会被过滤,不受行数变化影响;
- 方法3是PowerShell高版本的便捷写法,代码最简洁。
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

