如何使用PowerShell删除命令输出的最后一行?
输出如下所示:
[{"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
我想删除最后一行"+ line x hits“,值得一提的是,点击次数是动态的。
我试过了,但没有成功:
$linecounter = 0
$output=.\command.exe
while($linecounter -le 1)
{
foreach ($line in $output){
$linecounter=$linecounter+1
Write-Host $line
}
}
我能做什么?
发布于 2022-10-12 12:39:19
使用带有Select-Object
参数的-SkipLast
cmdlet跳过输出流中的最后一项:
$output = .\command.exe |Select-Object -SkipLast 1
发布于 2022-10-14 22:08:18
毫无疑问,马蒂亚斯·R·耶森的回答是从流输入中删除一个(或多个)输入对象(行)的的最佳解决方案。
.\command.exe
的(stdout)输出,然后Select-Object
-SkipLast 1
会传递除最后一行之外的所有输出。对于已经在内存中的数组(集合),中的 数组切片是更有效的替代(尽管使用小型数组可能无关紧要),尽管它的语法并不像PowerShell 7.2.x那样方便,因为它目前需要对数组的最大值进行显式引用。索引
# A 5-element sample array.
$output = 'line 1', 'line 2', 'line 3', 'line 4', 'line 5'
# Use array slicing to remove the last element.
# Note: Of necessity returns a *new* array, with the last element removed
$output[0..($output.Count-1 - 1)] # $output.Count-1 is the max. index
尽管PowerShell的数组(集合)索引([...]
)非常灵活,您可以使用负数引用相对于数组末尾的单个元素(例如,(1, 2, 3)[-1]
生成3
),但PowerShell截至7.2.x 不幸地缺乏将索引指定为元素 ranges的一部分的能力,这是其他语言(如Python )所支持的方式:
(1, 2, 3)[0..-1]
的东西不会像人们所期望的那样返回1, 2
,因为..
,即通用的距离算子,只是严格地根据其字面数字端点创建以下(临时)数组,然后其元素作为索引进入封闭数组:0, -1
;因此,(1, 2, 3)[0..-1]
相当于(1, 2, 3)[0, -1]
(!),因此返回1, 3
- Following the model of C#, `^` could be used to refer to the end of an array in `..` ranges; e.g.:
一厢情愿地想到PowerShell 7.2.x (1,2,3)0.^1# -> 1,2
https://stackoverflow.com/questions/74041779
复制相似问题