1

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
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the suggestion @Matt but no data is being captured in the test.txt file when I am running the script... :( Also FYI, my aim here is to capture the count of ":80" connections in the text file.
I didnt get any return either on your command in my text file. Just try the portion before the pipe netstat -an -p tcp to confirm the text file is populating. Do you get output on screen when you run your commnand?
Please see my updated answer. you need to encapsulate your variable in quotes so the command executes properly.
Forgive my error. I always referred to this which is what caused the mistake asciitable.com
You're probably using Windows-1252 or similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.