Mike C
Mike C

Reputation: 131

How do I capture StdOut from External programs from a PowerShell script?

I write VBScript script and often times I need to run a command line program and capture the the information that was written to std out so that output can be scraped. All of this is hidden from the person that executes the VBScript.

Here is an quick and stupid example:

cmd = "ping google.com"
Set objWSH = CreateObject( "WScript.Shell" ) 
Set Ret = objWSH.exec(cmd)
StdOut = Ret.StdOut.ReadAll()
myarray = Split(StdOut,vbcrlf)

For each line in myarray
  If Instr(line,"Average") then avg = Right(line,Len(line) - InStrRev(line," "))
Next

wscript.echo "Google.com = " & avg

My question is not "how do I ping" as I'm showing in my example code.

I need to know how to run command-line programs from within a PowerShell script so that they are not seen but in a way that I can grab the output written to std-out.

Upvotes: 1

Views: 813

Answers (2)

user6811411
user6811411

Reputation:

To be close to your vbscript but with a RegEx:

foreach ($line in (ping.exe google.com)){
  if ($line -match 'Average = (\d+)ms'){
    "Google.com = $($matches[1])"
  }
}

Sample output:

Google.com = 12

A more PowerShell way:

$Avg = (test-connection google.com).responsetime|measure -average|select -expandproperty Average
"Google.com = $Avg"

sample output:

Google.com = 25.25

Upvotes: 0

Phil M
Phil M

Reputation: 1619

Store the result in a variable.

$result = Invoke-Expression 'ping www.google.com'

or

$result = iex 'ping www.google.com'

Upvotes: 2

Related Questions