Swarnabha De
Swarnabha De

Reputation: 13

Run a command from cmd prompt and capture data in text file using vbscript

I am trying to run the below command from command prompt using vbscript and then capture the result in a text file.

netstat -an -p tcp | find /c ":80" > C:\Users\Swarnabha\Desktop\test.txt

I have written the below code but it is not working... Help me here plz!

Dim filepath
filepath= "C:\Users\Swarnabha\Desktop\test.txt"


Dim connstr
Dim portno

portno = ":80"
connstr = "cmd netstat -an -p tcp | find /c "& portno &" > "& filepath

Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run connstr

Set oShell = Nothing

WScript.Quit

Upvotes: 1

Views: 1073

Answers (1)

Matt
Matt

Reputation: 46690

I think what you need to do is edit the connstr to include the /c switch which carries out the command specified by the string and then terminates. You need to do that since you are specifying the > redirect command which "is a feature of the shell" to quote Bill Stewart.

connstr = "cmd.exe /c netstat -an -p tcp | find /c "& chr(34) & portno & chr(34) & " > " & filepath

You also need to put your port number variable in quote. 34 is the ANSI code for double quotes. That way your command will look like the following

cmd.exe /c netstat -an -p tcp | find /c ":80" > "C:\Users\Swarnabha\Desktop\test.txt"

I would consider as well grouping all your variable declarations as it is a good coding practice. You should also quote your filepath as that is likely to contain spaces at some point as well.

Upvotes: 2

Related Questions