Output a PowerShell object into a string

隐身守侯 提交于 2019-12-23 07:41:15

问题


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.


回答1:


Something like..

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

"start" + $string


来源:https://stackoverflow.com/questions/24661972/output-a-powershell-object-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!