string 将 PowerShell 对象输出为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24661972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:19:40  来源:igfitidea点击:

Output a PowerShell object into a string

stringpowershellformat

提问by johnnycrash

This code launches ping:

此代码启动 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 时,

$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?

所以问题是......您通常如何将来自 powershell 对象的漂亮字符串输出转换为字符串?

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 一词贴在我在 powershell 脚本的一行中单独键入 $Proc 时得到的正常输出前面。

START     27       3     1936       1852    10     0.02   6832 PING

But, "Start " + $Proc produces this:

但是, "Start " + $Proc 产生这个:

Start System.Diagnostics.Process (PING)

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

所以这就是为什么我想我会尝试将 $Proc 放入一个字符串中。

回答by arashid290

Something like..

就像是..

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

"start" + $string