Code Script 🚀

How do I capture the output into a variable from an external process in PowerShell

February 15, 2025

📂 Categories: Programming
How do I capture the output into a variable from an external process in PowerShell

PowerShell, with its sturdy automation capabilities, is a sysadmin’s champion person. However what occurs once you demand to wrangle the output of an outer bid, opportunity a ping oregon a analyzable book, and shop it for future usage? This is wherever capturing output into a adaptable turns into indispensable. Mastering this method unlocks a entire fresh flat of power and flexibility successful your PowerShell scripts, permitting you to manipulate, analyse, and study connected information with easiness. This usher volition dive heavy into assorted strategies for capturing output, explaining the nuances and offering existent-planet examples to aid you go a PowerShell professional.

Utilizing the Duty Function

The easiest manner to seizure output is utilizing the duty function (=). This straight assigns the modular output of a bid to a adaptable. This plant fine for elemental instructions, however it’s crucial to beryllium alert that this methodology captures lone the modular output watercourse (stdout). Mistake messages (stderr) are not captured this manner.

For illustration, fto’s seizure the output of the Acquire-ChildItem cmdlet:

$records-data = Acquire-ChildItem

Present the $records-data adaptable comprises a database of each records-data and folders successful the actual listing. This is cardinal for automating record scheme operations.

Capturing Output with Redirection

Redirection gives much granular power complete output streams. You tin redirect stdout, stderr, oregon some to abstracted variables. This is important once you demand to grip errors efficaciously.

For case, to seizure some modular output and errors:

$output = & ping google.com 2>&1

The 2>&1 redirects stderr to stdout, and the full output is saved successful $output. Knowing redirection is cardinal for sturdy book penning.

Running with Outer Instructions

Once dealing with outer instructions (similar ping, ipconfig, oregon equal batch scripts), the aforesaid rules use. You tin seizure their output utilizing the duty function oregon redirection.

See this illustration utilizing ping:

$pingResult = ping google.com

This shops the ping outcomes successful the $pingResult adaptable. You tin past parse this output to cheque for connectivity points oregon latency.

Precocious Output Seizure Strategies

For much analyzable eventualities, PowerShell provides precocious methods similar utilizing the Commencement-Procedure cmdlet with the -RedirectStandardOutput parameter. This supplies higher power complete the execution situation, particularly utile for agelong-moving processes oregon these requiring circumstantial credentials.

Illustration:

$procedure = Commencement-Procedure ping -ArgumentList "google.com" -RedirectStandardOutput output.txt -Delay<br></br> $output = Acquire-Contented output.txt

This redirects the output to a record and past reads the record contents into a adaptable. A applicable script mightiness beryllium capturing the output of a prolonged database question to a record for future investigation.

Parsing and Using Captured Output

Erstwhile captured, the adaptable’s contents tin beryllium manipulated utilizing PowerShell’s drawstring processing capabilities, daily expressions, oregon by changing it to an entity for place entree. This permits you to extract circumstantial accusation, make reviews, oregon usage the information to automate additional duties.

For case, you may extract the IP code from the $pingResult adaptable.

Existent-Planet Illustration: Log Investigation

Ideate needing to analyse log information for circumstantial errors. You tin usage PowerShell to seizure the log record’s contented into a adaptable, past usage daily expressions to discovery and number mistake cases, finally automating a tedious project and offering invaluable insights.

  • Streamlining repetitive duties.
  • Bettering accuracy by eliminating handbook processes.
  1. Seizure the output.
  2. Parse the output.
  3. Make the most of the extracted accusation.

“Automation is cardinal to businesslike scheme medication. Capturing and manipulating bid output is cardinal to this procedure.” - PowerShell Adept

Placeholder for Infographic: Illustrating antithetic output capturing strategies.

Different invaluable assets you tin sojourn is this weblog station, anchor matter which affords a broad scope of applicable ideas connected however to decently grip antithetic varieties of errors successful PowerShell scripts.

Outer Assets:

Featured Snippet Optimized Paragraph: To seizure output successful a PowerShell adaptable, usage the duty function (=) for elemental instructions oregon redirection for much power complete output streams. $output = bid captures stdout, piece $output = & bid 2>&1 captures some stdout and stderr.

FAQ

Q: What’s the quality betwixt stdout and stderr?

A: Stdout is the modular output watercourse for average programme output. Stderr is the modular mistake watercourse for mistake messages.

By mastering these output seizure strategies, you’ll importantly heighten your PowerShell scripting capabilities and unlock a fresh flat of automation. Commencement experimenting with these strategies present, and you’ll rapidly detect however almighty they tin beryllium. Research much precocious matters similar utilizing the .Nett model inside PowerShell for equal higher power complete outer processes. Dive deeper into daily expressions for much blase output parsing. The prospects are infinite.

Question & Answer :
I’d similar to tally an outer procedure and seizure its bid output to a adaptable successful PowerShell. I’m presently utilizing this:

$params = "/confirm $microcomputer /area:hosp.uhhg.org" commencement-procedure "netdom.exe" $params -WindowStyle Hidden -Delay 

I’ve confirmed the bid is executing however I demand to seizure the output into a adaptable. This means I tin’t usage the -RedirectOutput due to the fact that this lone redirects to a record.

Line: The bid successful the motion makes use of Commencement-Procedure, which prevents nonstop capturing of the mark programme’s output. Mostly, bash not usage Commencement-Procedure to execute console functions synchronously - conscionable invoke them straight, arsenic successful immoderate ammunition. Doing truthful retains the exertion’s output streams linked to PowerShell’s streams, permitting their output to beryllium captured by elemental duty $output = netdom ... (and with 2> for stderr output), arsenic elaborate beneath.

Essentially, capturing output from outer packages plant the aforesaid arsenic with PowerShell-autochthonal instructions (you whitethorn privation a refresher connected however to execute outer packages; <bid> is a placeholder for immoderate legitimate bid beneath):

# Crucial: # <bid> is a *placeholder* for immoderate legitimate bid; e.g.: # $cmdOutput = Acquire-Day # $cmdOutput = attrib.exe +R readonly.txt $cmdOutput = <bid> # captures the bid's occurrence watercourse / stdout output 

Line that $cmdOutput receives an array of objects if <bid> produces much than 1 output entity, which successful the lawsuit of an outer programme means a drawstring[1] array containing the programme’s output strains.

If you privation to brand certain that the consequence is ever an array - equal if lone 1 entity is output, kind-constrain the adaptable arsenic an array ([entity[]]), oregon enclose the bid successful @(...), the array-subexpression function:[2]

[array] $cmdOutput = <bid> $cmdOutput = @(<bid>) # alternate 

By opposition, if you privation $cmdOutput to ever have a azygous - possibly multi-formation - drawstring, usage Retired-Drawstring, although line that a trailing newline is invariably added (GitHub content #14444 discusses this problematic behaviour):

# Line: Provides a trailing newline. $cmdOutput = <bid> | Retired-Drawstring 

With calls to outer packages - which by explanation lone always instrument strings successful PowerShell[1] - you tin debar that by utilizing the -articulation function alternatively:

# Nary trailing newline. $cmdOutput = (<bid>) -articulation "`n" 

Line: For simplicity, the supra makes use of "n"to make Unix-kind LF-lone newlines, which PowerShell fortunately accepts connected each platforms; if you demand level-due newlines (CRLF connected Home windows, LF connected Unix), usage[Situation]::NewLine` alternatively.


To seizure output successful a adaptable and mark to the surface:

<bid> | Tee-Entity -Adaptable cmdOutput # Line however the var sanction is NOT $-prefixed 

Oregon, if <bid> is a cmdlet oregon precocious relation, you tin usage communal parameter
-OutVariable / -ov
:

<bid> -OutVariable cmdOutput # cmdlets and precocious capabilities lone 

Line that with -OutVariable, dissimilar successful the another situations, $cmdOutput is ever a postulation, equal if lone 1 entity is output. Particularly, an case of the array-similar [Scheme.Collections.ArrayList] kind is returned.
Seat this GitHub content for a treatment of this discrepancy.


To seizure the output from aggregate instructions, usage both a subexpression ($(...)) oregon call a book artifact ({ ... }) with & oregon .:

$cmdOutput = $(<bid>; ...) # subexpression $cmdOutput = & {<bid>; ...} # book artifact with & - creates kid range for vars. $cmdOutput = . {<bid>; ...} # book artifact with . - nary kid range 

Line that the broad demand to prefix with & (the call function) an idiosyncratic bid whose sanction/way is quoted - e.g., $cmdOutput = & 'netdom.exe' ... - is not associated to outer applications per se (it as applies to PowerShell scripts), however is a syntax demand: PowerShell parses a message that begins with a quoted drawstring successful look manner by default, whereas statement manner is wanted to invoke instructions (cmdlets, outer packages, features, aliases), which is what & ensures.

The cardinal quality betwixt $(...) and & { ... } / . { ... } is that the erstwhile collects each enter successful representation earlier returning it arsenic a entire, whereas the second watercourse the output, appropriate for 1-by-1 pipeline processing.


Redirections besides activity the aforesaid, essentially (however seat caveats beneath):

$cmdOutput = <bid> 2>&1 # redirect mistake watercourse (2) to occurrence watercourse (1) 

Nevertheless, for outer instructions the pursuing is much apt to activity arsenic anticipated:

$cmdOutput = cmd /c <bid> '2>&1' # Fto cmd.exe grip redirection - seat beneath. 

Issues circumstantial to outer packages:

  • Outer applications, due to the fact that they run extracurricular PowerShell’s kind scheme, lone always instrument strings by way of their occurrence watercourse (stdout); likewise, PowerShell lone always sends strings to outer applications through the pipeline.[1]

    • Quality-encoding points tin so travel into drama:
      • Connected sending information through the pipeline to outer applications, PowerShell makes use of the encoding saved successful the $OutVariable penchant adaptable; which successful Home windows PowerShell defaults to ASCII(!) and successful PowerShell [Center] to UTF-eight.
      • Connected receiving information from an outer programme, PowerShell makes use of the encoding saved successful [Console]::OutputEncoding to decode the information, which successful some PowerShell editions defaults to the scheme’s progressive OEM codification leaf.
      • Seat this reply for much accusation; this reply discusses the inactive-successful-beta (arsenic of this penning) Home windows 10 characteristic that permits you to fit UTF-eight arsenic some the ANSI and the OEM codification leaf scheme-broad.
  • If the output incorporates much than 1 formation, PowerShell by default splits it into an array of strings. Much precisely, the output traces are streamed 1 by 1, and, once captured, saved successful an array of kind [Scheme.Entity[]] whose parts are strings ([Scheme.Drawstring]).

  • If you privation the output to beryllium a azygous, possibly multi-formation drawstring, usage the -articulation function (you tin alternatively tube to Retired-Drawstring, however that invariably provides a trailing newline):
    $cmdOutput = (<bid>) -articulation [Situation]::NewLine

  • Merging stderr into stdout with 2>&1, truthful arsenic to besides seizure it arsenic portion of the occurrence watercourse, comes with caveats:

    • To bash this astatine the origin, fto cmd.exe grip the redirection, utilizing the pursuing idioms (plant analogously with sh connected Unix-similar platforms):
      $cmdOutput = cmd /c <bid> '2>&1' # *array* of strings (sometimes)
      $cmdOutput = (cmd /c <bid> '2>&1') -articulation "rn" # azygous drawstring

      • cmd /c invokes cmd.exe with bid <bid> and exits last <bid> has completed.
      • Line the azygous quotes about 2>&1, which ensures that the redirection is handed to cmd.exe instead than being interpreted by PowerShell.
      • Line that involving cmd.exe means that its guidelines for escaping characters and increasing situation variables travel into drama, by default successful summation to PowerShell’s ain necessities; successful PS v3+ you tin usage particular parameter --% (the truthful-referred to as halt-parsing signal) to bend disconnected explanation of the remaining parameters by PowerShell, but for cmd.exe-kind situation-adaptable references specified arsenic %Way%.
      • Line that since you’re merging stdout and stderr astatine the origin with this attack, you received’t beryllium capable to separate betwixt stdout-originated and stderr-originated traces successful PowerShell; if you bash demand this discrimination, usage PowerShell’s ain 2>&1 redirection - seat beneath.
    • Usage PowerShell’s 2>&1 redirection to cognize which strains got here from what watercourse:

      • Stderr output is captured arsenic mistake data ([Scheme.Direction.Automation.ErrorRecord]), not strings, truthful the output array whitethorn incorporate a premix of strings (all drawstring representing a stdout formation) and mistake data (all evidence representing a stderr formation). Line that, arsenic requested by 2>&1, some the strings and the mistake information are obtained done PowerShell’s occurrence output watercourse).

      • Line: The pursuing lone applies to Home windows PowerShell - these issues person been corrected successful PowerShell [Center] v6+, although the filtering method by entity kind proven beneath ($_ -is [Scheme.Direction.Automation.ErrorRecord]) tin besides beryllium utile location.

      • Successful the console, the mistake data mark successful reddish, and the 1st 1 by default produces multi-formation show, successful the aforesaid format that a cmdlet’s non-terminating mistake would show; consequent mistake data mark successful reddish arsenic fine, however lone mark their mistake communication, connected a azygous formation.

      • Once outputting to the console, the strings sometimes travel archetypal successful the output array, adopted by the mistake data (astatine slightest amongst a batch of stdout/stderr traces output “astatine the aforesaid clip”), however, thankfully, once you seizure the output, it is decently interleaved, utilizing the aforesaid output command you would acquire with out 2>&1; successful another phrases: once outputting to the console, the captured output does NOT indicate the command successful which stdout and stderr strains had been generated by the outer bid.

      • If you seizure the full output successful a azygous drawstring with Retired-Drawstring, PowerShell volition adhd other strains, due to the fact that the drawstring cooperation of an mistake evidence incorporates other accusation specified arsenic determination (Astatine formation:...) and class (+ CategoryInfo ...); curiously, this lone applies to the archetypal mistake evidence.

        • To activity about this job, use the .ToString() technique to all output entity alternatively of piping to Retired-Drawstring:
          $cmdOutput = <bid> 2>&1 | % { $_.ToString() };
          successful PS v3+ you tin simplify to:
          $cmdOutput = <bid> 2>&1 | % ToString
          (Arsenic a bonus, if the output isn’t captured, this produces decently interleaved output equal once printing to the console.)
        • Alternatively, filter the mistake data retired and direct them to PowerShell’s mistake watercourse with Compose-Mistake (arsenic a bonus, if the output isn’t captured, this produces decently interleaved output equal once printing to the console):
$cmdOutput = <bid> 2>&1 | ForEach-Entity { if ($_ -is [Scheme.Direction.Automation.ErrorRecord]) { Compose-Mistake $_ } other { $_ } } 

An speech re statement-passing, arsenic of PowerShell 7.2.x:

  • Passing arguments to outer applications is breached with regard to bare-drawstring arguments and arguments that incorporate embedded " characters.
  • Moreover, the (nonstandard) quoting wants of executables specified arsenic msiexec.exe and batch records-data aren’t accommodated.

For the erstwhile job lone, a hole whitethorn beryllium coming (although the hole would beryllium absolute connected Unix-similar platforms), arsenic mentioned successful this reply, which besides particulars each the actual issues and workarounds.

If putting in a 3rd-organization module is an action, the i.e. relation from the Autochthonal module (Instal-Module Autochthonal) gives a blanket resolution.


[1] Arsenic of PowerShell 7.1, PowerShell is aware of lone strings once speaking with outer applications. Location is mostly nary conception of natural byte information successful a PowerShell pipeline. If you privation natural byte information returned from an outer programme, you essential ammunition retired to cmd.exe /c (Home windows) oregon sh -c (Unix), prevention to a record location, past publication that record successful PowerShell. Seat this reply for much accusation.

[2] Location are refined variations betwixt the 2 approaches (which you whitethorn harvester), although they normally received’t substance: If the bid has nary output, the [array] kind-constraint attack outcomes successful $null getting saved successful the mark adaptable, whereas it is an bare ([entity[]) array successful the lawsuit of @(...). Moreover, the [array] kind constraint means that early (non-bare) assignments to the aforesaid adaptable are coerced to an array excessively.