1

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.

2
  • Yeah.. thats not powershell Commented Apr 28, 2017 at 2:40
  • 1
    PowerShell has a CmdLet for pinging... Test-Connection msdn.microsoft.com/powershell/reference/5.1/… Commented Apr 28, 2017 at 7:08

2 Answers 2

2

Store the result in a variable.

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

or

$result = iex 'ping www.google.com'
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.