【问题标题】:Output a PowerShell object into a string将 PowerShell 对象输出为字符串
【发布时间】:2018-12-29 22:18:53
【问题描述】:

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

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

$Proc

我明白了:

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

我想把数据线变成一个字符串。

所以我尝试了这个:

$Proc | Format-table -HideTableHeaders

我得到了这个:

 27       3     1936       1852    10     0.02   6832 PING

我试过了:

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

得到了这个:

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

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

最终,我要做的就是在我的 powershell 脚本的一行中单独键入 $Proc 时,将 START 这个词放在我得到的正常输出前面。

START     27       3     1936       1852    10     0.02   6832 PING

但是,“开始” + $Proc 会产生这样的结果:

Start System.Diagnostics.Process (PING)

这就是为什么我想尝试将 $Proc 转换为字符串的原因。

【问题讨论】:

  • 你为什么不在Format-Table 之后将它通过管道传送到Out-String

标签: string powershell format


【解决方案1】:

有点像..

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

"start" + $string

【讨论】:

  • 酷,谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-08-28
  • 2012-05-13
  • 2012-01-26
  • 2011-10-02
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2016-01-21
相关资源
最近更新 更多