Reputation: 753
I have a simple powershell script
$proc = Get-Process -id 412
$proc
it's return such output
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
434 26 65768 109144 6,42 412 1 browser
how can i get this output to a variable so i can use it somewhere else in script?
I tryed to use it likes this
$proc = Get-Process -id 412
Write-Host $proc
but it gives me not same output as $proc is a instance of "System.Diagnostics.Process" class
System.Diagnostics.Process (browser)
Upvotes: 4
Views: 5074
Reputation: 437100
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 this answer for details.
If you explicitly want to print to the display (host) only while using rich formatting, use
Out-Host
instead:
$proc | Out-Host # rich formatting, display output only
The Out-String
cmdlet uses the same formatting and returns the formatted representation as data, in the form of a single, multi-line string
(by default).
However, if there's no concern about accidentally producing data output, via PowerShell's success output stream (see about_Redirection), you can simply use PowerShell's implicit output behavior, which also results in rich formatting if the data is ultimately sent to the display (in the absence of getting captured in a variable, sent through the pipeline, or getting redirected):
# Implicit output to the success stream, which, if not captured or redirected,
# prints to the display *by default*, richly formatted.
$proc
The above is the implicit - and generally preferable - equivalent of Write-Output $proc
; explicit use of Write-Output
, whose purpose is to write to the success output stream, is rarely needed; see this answer for additional information.
Upvotes: 5
Reputation: 647
It depends on exactly what you mean. $proc is an object with properties. If you do $x = $proc | out-string
then $x
will be the string representation of the default view. However in terms of using it later you might like to do write-host $proc.Handles $proc.NPM $proc.PM $proc.WS $proc.CPU $proc.id $proc.SI $proc.ProcessName
to access each of the individual elements.
Upvotes: 1
Reputation: 753
Found solution that give me same output result
$proc = Get-Process -id 412
$str = Out-String -InputObject $proc
Write-Host $str
Upvotes: 1