Easily grab one-liner output of system commands [Windows]

Share your advanced PureBasic knowledge/code with the community.
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Easily grab one-liner output of system commands [Windows]

Post by firace »

Just a very simple (quick and dirty) procedure that can make your life easier...

Idea is to have a more convenient way of getting one-liner output than fiddling with runProgram+readProgramString syntax all the time.

Note: only tested with simple commands.

Code: Select all


Procedure.s outputOf(externalCommand.s)   ;; for one-liners with one-line output :)
  
  externalCommand = ReplaceString(externalCommand,"'",Chr(34))
  
  outputStream = RunProgram("cmd" , "/c " + externalCommand, "", #PB_Program_Open|#PB_Program_Read|#PB_Program_Hide)
  
  Repeat 
    o.s = ReadProgramString(outputStream ) 
    i+1
  Until o.s <> "" Or i > 3
  
  ProcedureReturn o
EndProcedure


;;; Examples 

OpenConsole("Test")

PrintN( OutputOf("netsh interface ip show interface 12 | find 'State  '" ))
PrintN( OutputOf("ping www.google.com -n 1"  ))
PrintN( OutputOf("ipconfig  |  find 'IPv4' " ))

Delay(999)

Dude
Addict
Addict
Posts: 1907
Joined: Mon Feb 16, 2015 2:49 pm

Re: Easily grab one-liner output of system commands [Window

Post by Dude »

firace wrote:Idea is to have a more convenient way of getting one-liner output than fiddling with runProgram+readProgramString syntax all the time.
But... your example uses both RunProgram() and ReadProgramString()... :?:
firace
Addict
Addict
Posts: 899
Joined: Wed Nov 09, 2011 8:58 am

Re: Easily grab one-liner output of system commands [Window

Post by firace »

Dude wrote:
firace wrote:Idea is to have a more convenient way of getting one-liner output than fiddling with runProgram+readProgramString syntax all the time.
But... your example uses both RunProgram() and ReadProgramString()... :?:

Well of course the implementation of OutputOf uses them... so you don't have to.

Using this, you can simply write A instead of B:

A

Code: Select all

PrintN( OutputOf("netsh interface ip show interface 12 | find 'State  '" ))
B

Code: Select all

PrintN( ReadProgramString(RunProgram("cmd" , "/c netsh interface ip show interface 12 | find " + chr(34) + "State " + chr(34) , "", #PB_Program_Open|#PB_Program_Read|#PB_Program_Hide) ) ) 
As I use this type of command quite often, this makes my life a lot easier.
Post Reply