Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a PowerShell object into a string

This code launches ping:

$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$ProcessInfo.FileName = "ping.exe"
$ProcessInfo.RedirectStandardError = $true
$ProcessInfo.RedirectStandardOutput = $true
$ProcessInfo.UseShellExecute = $false
$ProcessInfo.Arguments = "localhost"
$Proc = New-Object System.Diagnostics.Process
$Proc.StartInfo = $ProcessInfo
$Proc.Start() | Out-Null

When I type $Proc at the command,

$Proc

I get this:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     27       3     1936       1852    10     0.02   6832 PING

I want to get the data line into a string.

So I tried this:

$Proc | Format-table -HideTableHeaders

And I got this:

 27       3     1936       1852    10     0.02   6832 PING

I tried this:

$Foo = $Proc | Format-table -HideTableHeaders
$Foo

And got this:

Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData

So the question is... How do you typically get the nice string output from a powershell object into a string?

Ultimately all I'm trying to do is stick the word START in front of the normal output I get when I just type $Proc by itself on a line in my powershell script.

START     27       3     1936       1852    10     0.02   6832 PING

But, "Start " + $Proc produces this:

Start System.Diagnostics.Process (PING)

So that's why I thought I'd try to get $Proc into a string.

like image 982
johnnycrash Avatar asked Jul 09 '14 19:07

johnnycrash


Video Answer


1 Answers

Something like..

$string = $proc | Format-Table -HideTableHeaders | Out-String

"start" + $string
like image 120
arashid290 Avatar answered Oct 06 '22 18:10

arashid290