I need to be able to launch a process and read the output into a variable. Then based on the return of the command I can choose to show the full output or just a selected subset.
So to be clear, I want to launch a text based process (psexec actually) and read the output from that command (stdout, stderr, etc) into a variable rather than have it directly outputted to the console.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
Type “Write-Output” in the scripting pane of the “PowerShell ISE“, and then write hyphen (-). A dropdown menu will be activated, which contains the supported parameter: For instance, the echo/Write-Output command prints the output as an individual expression.
From the about_Operators help topic: :: Static member operator Calls the static properties operator and methods of a .NET Framework class. To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. [
You left off some details regarding what kind of process, but I think this article from the Powershell Team Blog has whatever you'd like to do, either from piping the executable's output somewhere or utilizing System.Diagnostics.Process
.
Now that the second option sounds like what you want to do, you can use the ProcessStartInfo
class to feed in true
as the RedirectStandardOutput
property, and then read from the StandardOutput
property of the Process
object to do whatever you want with the output. StandardError
works identically.
As far as reading stuff into variables is concerned, you should just be able to do something like
$output = ps
This will only capture stdout, though, not the verbose, warning or error streams. You can get the exit code of the previous command by testing the special variable $?
.
I think a little more information would be of use to provide a more complete answer, but hopefully this is some way towards what you're looking for.
The PowerShell Community Extensions includes Start-Process. This actually returns a System.Diagnostics.Process.
> $proc = Start-Process pslist -NoShellExecute
However, while this returns the Process object it does not allow you to redirect the output prior to executing. To do that one can create their own process and execute it by first modifying the ProcessStartInfo members:
> $proc = New-Object System.Diagnostics.Process
> $proc.StartInfo = New-Object System.Diagnostics.ProcessStartInfo("pslist.exe")
> $proc.StartInfo.CreateNoWindow = $true
> $proc.StartInfo.UseShellExecute = $false
> $proc.StartInfo.RedirectStandardOutput = $true
> $proc.Start()
> $proc.StandardOutput.ReadToEnd()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With