Home > database >  How to delete last line of a multiline command output in powershell
How to delete last line of a multiline command output in powershell

Time:10-13

How can I delete the last line of a command output with PowerShell?

The output looks like this:

[{"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":"%37"},"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

I want to delete the last line "[ ] Found x hits" and it is worth to mention, that the number of hits is dynamic.

I have tried this, but didn't work:

$linecounter = 0
$output=.\command.exe

while($linecounter -le 1)  
{  
    foreach ($line in $output){
      $linecounter=$linecounter 1
      Write-Host $line

    }
}  

What can i do?

CodePudding user response:

Use the Select-Object cmdlet with the -SkipLast parameter to skip the last item in a stream of output:

$output = .\command.exe |Select-Object -SkipLast 1
  • Related