将PowerShell对象输出到字符串中

joh*_*ash 9 string format powershell

此代码启动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
Run Code Online (Sandbox Code Playgroud)

当我在命令中输入$ Proc时,

$Proc
Run Code Online (Sandbox Code Playgroud)

我明白了:

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

我想将数据行转换为字符串.

所以我尝试了这个:

$Proc | Format-table -HideTableHeaders
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

 27       3     1936       1852    10     0.02   6832 PING
Run Code Online (Sandbox Code Playgroud)

我试过这个:

$Foo = $Proc | Format-table -HideTableHeaders
$Foo
Run Code Online (Sandbox Code Playgroud)

得到了这个:

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
Run Code Online (Sandbox Code Playgroud)

所以问题是......你如何通常将PowerShell对象的字符串输出变为字符串?

最后,我想要做的就是在我的powershell脚本中单独输入$ Proc时,在正常输出前面加上START一词.

START     27       3     1936       1852    10     0.02   6832 PING
Run Code Online (Sandbox Code Playgroud)

但是,"开始"+ $ Proc产生了这个:

Start System.Diagnostics.Process (PING)
Run Code Online (Sandbox Code Playgroud)

所以这就是为什么我认为我会尝试将$ Proc变成一个字符串.

小智 15

就像是..

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

"start" + $string
Run Code Online (Sandbox Code Playgroud)