Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Delimiter into PowerShell Output

Tags:

powershell

The result of Get-Process -Name explorer | select Handles,WS,CPU,Id,ProcessName | ft -HideTableHeaders returns the following output:

2623 255336448 178.125 10080 explorer 

In order to ingest this data into a third party system, I need to pipe delimit the result as such:

2623|255336448|178.125|10080|explorer 

What is the best way to achieve this?

like image 956
user3342256 Avatar asked May 09 '26 01:05

user3342256


2 Answers

How about:

(Get-Process explorer |
  Select-Object Handles,Ws,CPU,ID,ProcessName |
  ConvertTo-Csv -Delimiter '|' -NoTypeInformation |
  Select-Object -Skip 1) -replace '"',''

Only use ft (Format-Table) for easy viewing in the PowerShell console (it's not good for sending data to other applications, because then you would have to undo the formatting - so don't format in the first place).

like image 66
Bill_Stewart Avatar answered May 11 '26 14:05

Bill_Stewart


To offer a more concise (and slightly faster) alternative to Bill Stewart's helpful answer:

Get-Process -Name explorer | ForEach-Object { 
  $(foreach ($prop in 'Handles', 'WS', 'CPU', 'Id', 'ProcessName') { $_.$prop }) -join '|'
}
  • foreach ($prop in 'Handles', 'WS', 'CPU', 'Id', 'ProcessName') { $_.$prop } outputs all the properties of interest for each process object ($_, the input object at hand provided by the ForEach-Object cmdlet).

  • $(...) collects them as an [object[]] array, which ...

  • ... enables that array's use as the LHS of the -join operator in order to join the array's elements with | as the separator to form a single string.

Overall, you get a single string per input object, as desired.

like image 25
mklement0 Avatar answered May 11 '26 16:05

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!