如何将输出输出到变量
How get output to a variable
我有一个简单的 powershell 脚本
$proc = Get-Process -id 412
$proc
就是return这样的输出
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
434 26 65768 109144 6,42 412 1 browser
我怎样才能将这个输出输出到一个变量,以便我可以在脚本的其他地方使用它?
我试过这样使用它
$proc = Get-Process -id 412
Write-Host $proc
但它给我的输出不一样,因为 $proc 是“System.Diagnostics.Process”的一个实例 class
System.Diagnostics.Process (browser)
找到了给我相同输出结果的解决方案
$proc = Get-Process -id 412
$str = Out-String -InputObject $proc
Write-Host $str
这取决于你的意思。 $proc 是一个具有属性的对象。如果您执行 $x = $proc | out-string
,则 $x
将是默认视图的字符串表示形式。但是,就以后使用它而言,您可能希望 write-host $proc.Handles $proc.NPM $proc.PM $proc.WS $proc.CPU $proc.id $proc.SI $proc.ProcessName
访问每个单独的元素。
Write-Host
, whose purpose is to write directly to the display, does not use PowerShell's rich output formatting system - it uses simple .ToString()
formatting instead, which often results in unhelpful representations - see 了解详情。
如果您在使用富格式时明确希望打印到显示器(主机)仅,请使用
Out-Host
改为 :
$proc | Out-Host # rich formatting, display output only
Out-String
cmdlet 使用与 data 相同的格式和 returns 格式化表示,形式为单个,多行字符串
(默认)。
但是,如果不担心意外产生 数据 输出,通过 PowerShell 的 成功输出流 (参见 about_Redirection) , 您可以简单地使用 PowerShell 的 隐式输出 行为,如果数据最终发送到显示器(在没有在变量中捕获、通过管道发送或重定向):
# Implicit output to the success stream, which, if not captured or redirected,
# prints to the display *by default*, richly formatted.
$proc
以上是 Write-Output $proc
的隐式且通常更可取的等价物;很少需要显式使用 Write-Output
,其目的是写入 成功输出流 。
我有一个简单的 powershell 脚本
$proc = Get-Process -id 412
$proc
就是return这样的输出
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
434 26 65768 109144 6,42 412 1 browser
我怎样才能将这个输出输出到一个变量,以便我可以在脚本的其他地方使用它?
我试过这样使用它
$proc = Get-Process -id 412
Write-Host $proc
但它给我的输出不一样,因为 $proc 是“System.Diagnostics.Process”的一个实例 class
System.Diagnostics.Process (browser)
找到了给我相同输出结果的解决方案
$proc = Get-Process -id 412
$str = Out-String -InputObject $proc
Write-Host $str
这取决于你的意思。 $proc 是一个具有属性的对象。如果您执行 $x = $proc | out-string
,则 $x
将是默认视图的字符串表示形式。但是,就以后使用它而言,您可能希望 write-host $proc.Handles $proc.NPM $proc.PM $proc.WS $proc.CPU $proc.id $proc.SI $proc.ProcessName
访问每个单独的元素。
Write-Host
, whose purpose is to write directly to the display, does not use PowerShell's rich output formatting system - it uses simple .ToString()
formatting instead, which often results in unhelpful representations - see
如果您在使用富格式时明确希望打印到显示器(主机)仅,请使用
Out-Host
改为 :
$proc | Out-Host # rich formatting, display output only
Out-String
cmdlet 使用与 data 相同的格式和 returns 格式化表示,形式为单个,多行字符串
(默认)。
但是,如果不担心意外产生 数据 输出,通过 PowerShell 的 成功输出流 (参见 about_Redirection) , 您可以简单地使用 PowerShell 的 隐式输出 行为,如果数据最终发送到显示器(在没有在变量中捕获、通过管道发送或重定向):
# Implicit output to the success stream, which, if not captured or redirected,
# prints to the display *by default*, richly formatted.
$proc
以上是 Write-Output $proc
的隐式且通常更可取的等价物;很少需要显式使用 Write-Output
,其目的是写入 成功输出流 。