vbscript code to read input from text file avoiding manual efforts - vbscript

I am drilling down Internet to get Vbscript code, where input is read from text file one per line and pass it to the commands in script. I am just a beginner and need help with this.
Basically I am gathering script to get pending patches of servers in our environment. The script looks like below:
'#
'# ServerPendingUpdates.vbs
'#
'# Usage: cscript ServerPendingUpdates.vbs {servername} {servername} {servername} {servername}
'# If no {servername} specified then 'localhost' assumed
'#
'# To do: Error handling
'#
Option Explicit
Dim strServer : strServer = GetArgValue(0,"localhost")
'#
'# Loop through the input parameters for each server
'#
Dim i
For i = 0 To WScript.Arguments.Count - 1
CheckServerUpdateStatus GetArgValue(i,"localhost") 'strServer
Next
WScript.Quit(0)
Function CheckServerUpdateStatus( ByVal strServer )
WScript.Echo vbCRLF & "Connecting to " & strServer & " to check software update status..."
Dim blnRebootRequired : blnRebootRequired = False
Dim blnRebootPending : blnRebootPending = False
Dim objSession : Set objSession = CreateObject("Microsoft.Update.Session", strServer)
Dim objUpdateSearcher : Set objUpdateSearcher = objSession.CreateUpdateSearcher
Dim objSearchResult : Set objSearchResult = objUpdateSearcher.Search(" IsAssigned=1 and IsHidden=0 and Type='Software'")
'#
'#
'#
Dim i, objUpdate
Dim intPendingInstalls : intPendingInstalls = 0
For i = 0 To objSearchResult.Updates.Count-1
Set objUpdate = objSearchResult.Updates.Item(I)
If objUpdate.IsInstalled Then
If objUpdate.RebootRequired Then
blnRebootPending = True
End If
Else
intPendingInstalls = intPendingInstalls + 1
'If objUpdate.RebootRequired Then '### This property is FALSE before installation and only set to TRUE after installation to indicate that this patch forced a reboot.
If objUpdate.InstallationBehavior.RebootBehavior <> 0 Then
'# http://msdn.microsoft.com/en-us/library/aa386064%28v=VS.85%29.aspx
'# InstallationBehavior.RebootBehavior = 0 Never reboot
'# InstallationBehavior.RebootBehavior = 1 Must reboot
'# InstallationBehavior.RebootBehavior = 2 Can request reboot
blnRebootRequired = True
End If
End If
Next
WScript.Echo strServer & " has " & intPendingInstalls & " updates pending installation"
If blnRebootRequired Then
WScript.Echo strServer & " WILL need to be rebooted to complete the installation of these updates."
Else
WScript.Echo strServer & " WILL NOT require a reboot to install these updates."
End If
'#
'#
'#
If blnRebootPending Then
WScript.Echo strServer & " is waiting for a REBOOT to complete a previous installation."
End If
End Function
'#
'#
'#
Function GetArgValue( intArgItem, strDefault )
If WScript.Arguments.Count > intArgItem Then
GetArgValue = WScript.Arguments.Item(intArgItem)
Else
GetArgValue = strDefault
End If
End Function
Basically I am looking for a code to put in somewhere there, where the server names input that shall be manually given after command execution in CLI can be given in a text file; like a lot of servers in text file and each server is executed one per line, one at a time by the script.
Cheers!

This allow to read from arguments collection and from standard input when - is passed as argument
Dim server
For Each server in WScript.Arguments.UnNamed
If server="-" Then
Do While Not WScript.StdIn.AtEndOfStream
WScript.Echo "Redirected: " + WScript.StdIn.ReadLine
Loop
Else
WScript.Echo "Argument: " + server
End If
Next
This allow to still pass arguments in the command line, and, if any of the arguments is a dash, the stantdard input is read. This will allow you to do any of the following
Usual argument pass
cscript checkServers.vbs server1 server2
Arguments and piped input
type servers.txt | cscript checkServers.vbs server1 server2 -
Only redirected input
cscript checkServers.vbs - < servers.txt
Redirected input and arguments
< servers.txt cscript checkServers.vbs - serverx
Or any other needed combination of arguments and standard input
type servers.txt | cscript checkservers.vbs server1 server2 - aditionalServer
EDITED to answer to comments
Option Explicit
Dim strServer
If WScript.Arguments.UnNamed.Length < 1 Then
CheckServerUpdateStatus "localhost"
Else
For Each strServer in WScript.Arguments.UnNamed
If strServer="-" Then
Do While Not WScript.StdIn.AtEndOfStream
strServer = Trim(WScript.StdIn.ReadLine)
If Len(strServer) > 0 Then CheckServerUpdateStatus strServer
Loop
Else
CheckServerUpdateStatus strServer
End If
Next
End If
WScript.Quit(0)
Obviously, you need to maintain your CheckServerUpdateStatus function, this code only handles the parameter input.

If you are trying to get the pending windows update installs for a bunch of computers, you can use this in Powershell:
$computers = gc text_file_of_computers.txt
ForEach ($computer in $computers) {
("-" * 30)+"`n" # Horizontal line
Write-Host "Patches not yet installed for $($computer)" -f "Yellow"
Get-Hotfix -co $computer| Where {$_.InstalledOn -eq $null}
"`n"+("-" * 30) # Horizontal line
}
As you can see, we only show patches which have a $null value for InstalledOn, which means they have not been installed as yet.
powershell

Related

Vbs print to console [duplicate]

What is the command or the quickest way to output results to console using vbscript?
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.
This was found on Dragon-IT Scripts and Code Repository.
You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
There are five ways to output text to the console:
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.
WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.
StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.
I came across this post and went back to an approach that I used some time ago which is similar to #MadAntrax's.
The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.
This assumes that your objective is to stream output to the console, rather than having output go to message boxes.
The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:
Option Explicit
'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE
'// Now we can use the Consol object to write to and read from the console
With CONS
'// Simply write a line
.print "CSCRIPT Console demo script"
'// Arguments are passed through correctly, if present
.Print "Arg count=" & wscript.arguments.count
'// List all the arguments on the console log
dim ix
for ix = 0 to wscript.arguments.count -1
.print "Arg(" & ix & ")=" & wscript.arguments(ix)
next
'// Prompt for some text from the user
dim sMsg : sMsg = .prompt( "Enter any text:" )
'// Write out the text in a box
.Box sMsg
'// Pause with the message "Hit enter to continue"
.Pause
End With
'= =========== End of script - the cCONSOLE class code follows here
Here is the code for the cCONSOLE class
CLASS cCONSOLE
'= =================================================================
'=
'= This class provides automatic switch to CScript and has methods
'= to write to and read from the CSCript console. It transparently
'= switches to CScript if the script has been started in WScript.
'=
'= =================================================================
Private oOUT
Private oIN
Private Sub Class_Initialize()
'= Run on creation of the cCONSOLE object, checks for cScript operation
'= Check to make sure we are running under CScript, if not restart
'= then run using CScript and terminate this instance.
dim oShell
set oShell = CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
'= Not running under CSCRIPT
'= Get the arguments on the command line and build an argument list
dim ArgList, IX
ArgList = ""
For IX = 0 to wscript.arguments.count - 1
'= Add the argument to the list, enclosing it in quotes
argList = argList & " """ & wscript.arguments.item(IX) & """"
next
'= Now restart with CScript and terminate this instance
oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
WScript.Quit
End If
'= Running under CScript so OK to continue
set oShell = Nothing
'= Save references to stdout and stdin for use with Print, Read and Prompt
set oOUT = WScript.StdOut
set oIN = WScript.StdIn
'= Print out the startup box
StartBox
BoxLine Wscript.ScriptName
BoxLine "Started at " & Now()
EndBox
End Sub
'= Utility methods for writing a box to the console with text in it
Public Sub StartBox()
Print " " & String(73, "_")
Print " |" & Space(73) & "|"
End Sub
Public Sub BoxLine(sText)
Print Left(" |" & Centre( sText, 74) , 75) & "|"
End Sub
Public Sub EndBox()
Print " |" & String(73, "_") & "|"
Print ""
End Sub
Public Sub Box(sMsg)
StartBox
BoxLine sMsg
EndBox
End Sub
'= END OF Box utility methods
'= Utility to center given text padded out to a certain width of text
'= assuming font is monospaced
Public Function Centre(sText, nWidth)
dim iLen
iLen = len(sText)
'= Check for overflow
if ilen > nwidth then Centre = sText : exit Function
'= Calculate padding either side
iLen = ( nWidth - iLen ) / 2
'= Generate text with padding
Centre = left( space(iLen) & sText & space(ilen), nWidth )
End Function
'= Method to write a line of text to the console
Public Sub Print( sText )
oOUT.WriteLine sText
End Sub
'= Method to prompt user input from the console with a message
Public Function Prompt( sText )
oOUT.Write sText
Prompt = Read()
End Function
'= Method to read input from the console with no prompting
Public Function Read()
Read = oIN.ReadLine
End Function
'= Method to provide wait for n seconds
Public Sub Wait(nSeconds)
WScript.Sleep nSeconds * 1000
End Sub
'= Method to pause for user to continue
Public Sub Pause
Prompt "Hit enter to continue..."
End Sub
END CLASS
Create a .vbs with the following code, which will open your main .vbs:
Set objShell = WScript.CreateObject("WScript.shell")
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""
Here is my main .vbs
Option Explicit
Dim i
for i = 1 To 5
Wscript.Echo i
Wscript.Sleep 5000
Next
You can run this script to echo in the command line
set wshShell = createObject("wscript.shell")
wshShell.run"cmd.exe /c echo something",1
For console output I use a snippet that quits elegantly if run in the wrong run-time. (And print is shorter to type...)
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
print "hello"

VB Script that needs to read from a text file

I have a VB Script that goes out to a string of servers and checks to see if there are any pending Windows updates. It works perfectly. The only issue is to run the script I have to type:
cscript pending.vbs server01 server02 server03 server04 etc.. I have over 300 servers I want to run this against. I need to be able to update a text file with server names instead of manually typing them out. I am posting the script below:
I am not a programmer by far, but I do understand some.
Thanks!
'#
'# ServerPendingUpdates.vbs
'#
'# Usage: cscript ServerPendingUpdates.vbs {servername} {servername} {servername} {servername}
'# If no {servername} specified then 'localhost' assumed
'#
'# To do: Error handling
'#
Option Explicit
Dim strServer : strServer = GetArgValue(0,"localhost")
'#
'# Loop through the input parameters for each server
'#
Dim i
For i = 0 To WScript.Arguments.Count - 1
CheckServerUpdateStatus GetArgValue(i,"localhost") 'strServer
Next
WScript.Quit(0)
Function CheckServerUpdateStatus( ByVal strServer )
WScript.Echo vbCRLF & "Connecting to " & strServer & " to check software update status..."
Dim blnRebootRequired : blnRebootRequired = False
Dim blnRebootPending : blnRebootPending = False
Dim objSession : Set objSession = CreateObject("Microsoft.Update.Session", strServer)
Dim objUpdateSearcher : Set objUpdateSearcher = objSession.CreateUpdateSearcher
Dim objSearchResult : Set objSearchResult = objUpdateSearcher.Search(" IsAssigned=1 and IsHidden=0 and Type='Software'")
'#
'#
'#
Dim i, objUpdate
Dim intPendingInstalls : intPendingInstalls = 0
For i = 0 To objSearchResult.Updates.Count-1
Set objUpdate = objSearchResult.Updates.Item(I)
If objUpdate.IsInstalled Then
If objUpdate.RebootRequired Then
blnRebootPending = True
End If
Else
intPendingInstalls = intPendingInstalls + 1
'If objUpdate.RebootRequired Then '### This property is FALSE before installation and only set to TRUE after installation to indicate that this patch forced a reboot.
If objUpdate.InstallationBehavior.RebootBehavior <> 0 Then
'# http://msdn.microsoft.com/en-us/library/aa386064%28v=VS.85%29.aspx
'# InstallationBehavior.RebootBehavior = 0 Never reboot
'# InstallationBehavior.RebootBehavior = 1 Must reboot
'# InstallationBehavior.RebootBehavior = 2 Can request reboot
blnRebootRequired = True
End If
End If
Next
WScript.Echo strServer & " has " & intPendingInstalls & " updates pending installation"
If blnRebootRequired Then
WScript.Echo strServer & " WILL need to be rebooted to complete the installation of these updates."
Else
WScript.Echo strServer & " WILL NOT require a reboot to install these updates."
End If
'#
'#
'#
If blnRebootPending Then
WScript.Echo strServer & " is waiting for a REBOOT to complete a previous installation."
End If
End Function
'#
'#
'#
Function GetArgValue( intArgItem, strDefault )
If WScript.Arguments.Count > intArgItem Then
GetArgValue = WScript.Arguments.Item(intArgItem)
Else
GetArgValue = strDefault
End If
End Function
You can query all domain using an ASDI object in vbs:
Set DomObj = GetObject("WinNT://" & strDomain )
DomObj.Filter = Array("computer")
Will output an array (DomObj)
or use LDAP:
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
strQuery = "<LDAP://" & strDNSDomain & "> (objectCategory=computer);distinguishedName,operatingSystem;subtree"
Source:
http://www.scriptlook.com/list-servers-domain/ &
http://www.scriptlook.com/check-services-every-server-domain/
Just create a text file with the list of servers, one per line.
Open the file (OpenTextFile) and read it line by line. See these links for reference
http://ss64.com/vb/filesystemobject.html
FileSystemObject Object
path = "serverlist.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path, 1)
Do Until objFile.AtEndOfStream
CheckServerUpdateStatus(objFile.ReadLine)
Loop

VBSCRIPT: TRACERT and PING a WEBADDRESS and write to text file without command promot popup

I need to write a diagnostic utility in VBS which i will package in my windows application installer.
I want the utility to run silently when the user is installing the application.
I tried:
Set pingCXS = objShell.Run("tracert -h 9 webaddress", 0, True)
Set pingCXSOutput = pingCXS.StdOut
strpingCXSOutput = pingCXSOutput.ReadAll
but it returns only the error code not the whole ping information.
When i use run method it gives a command window pop up:
Any other method to traceRT the webaddress without windows popup?
Also using a batch file is not a good option for me, as i have to use some WMI queries in the utility, which will require admin rights in batch file...
Please help out
Try this code :
Option Explicit
Dim ws,fso,TmpLogFile,Logfile,MyCmd,Webaddress,Param
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
TmpLogFile = "TmpFile.txt"
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "log"
If fso.FileExists(LogFile) Then fso.DeleteFile LogFile
webaddress = "www.stackoverflow.com"
Param = "-h 9"
MyCmd = "Tracert " & Param & " " & Webaddress & " >> "& TmpLogFile &_
" & cmd /U /C Type " & TmpLogFile & " > " & LogFile & " & Del " & TmpLogFile & ""
Call Run(MyCmd,0,True)
ws.run LogFile
'**********************************************************************************************
Function Run(StrCmd,Console,bWaitOnReturn)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function

vbscript output to console

What is the command or the quickest way to output results to console using vbscript?
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.
This was found on Dragon-IT Scripts and Code Repository.
You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
There are five ways to output text to the console:
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.
WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.
StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.
I came across this post and went back to an approach that I used some time ago which is similar to #MadAntrax's.
The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.
This assumes that your objective is to stream output to the console, rather than having output go to message boxes.
The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:
Option Explicit
'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE
'// Now we can use the Consol object to write to and read from the console
With CONS
'// Simply write a line
.print "CSCRIPT Console demo script"
'// Arguments are passed through correctly, if present
.Print "Arg count=" & wscript.arguments.count
'// List all the arguments on the console log
dim ix
for ix = 0 to wscript.arguments.count -1
.print "Arg(" & ix & ")=" & wscript.arguments(ix)
next
'// Prompt for some text from the user
dim sMsg : sMsg = .prompt( "Enter any text:" )
'// Write out the text in a box
.Box sMsg
'// Pause with the message "Hit enter to continue"
.Pause
End With
'= =========== End of script - the cCONSOLE class code follows here
Here is the code for the cCONSOLE class
CLASS cCONSOLE
'= =================================================================
'=
'= This class provides automatic switch to CScript and has methods
'= to write to and read from the CSCript console. It transparently
'= switches to CScript if the script has been started in WScript.
'=
'= =================================================================
Private oOUT
Private oIN
Private Sub Class_Initialize()
'= Run on creation of the cCONSOLE object, checks for cScript operation
'= Check to make sure we are running under CScript, if not restart
'= then run using CScript and terminate this instance.
dim oShell
set oShell = CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
'= Not running under CSCRIPT
'= Get the arguments on the command line and build an argument list
dim ArgList, IX
ArgList = ""
For IX = 0 to wscript.arguments.count - 1
'= Add the argument to the list, enclosing it in quotes
argList = argList & " """ & wscript.arguments.item(IX) & """"
next
'= Now restart with CScript and terminate this instance
oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
WScript.Quit
End If
'= Running under CScript so OK to continue
set oShell = Nothing
'= Save references to stdout and stdin for use with Print, Read and Prompt
set oOUT = WScript.StdOut
set oIN = WScript.StdIn
'= Print out the startup box
StartBox
BoxLine Wscript.ScriptName
BoxLine "Started at " & Now()
EndBox
End Sub
'= Utility methods for writing a box to the console with text in it
Public Sub StartBox()
Print " " & String(73, "_")
Print " |" & Space(73) & "|"
End Sub
Public Sub BoxLine(sText)
Print Left(" |" & Centre( sText, 74) , 75) & "|"
End Sub
Public Sub EndBox()
Print " |" & String(73, "_") & "|"
Print ""
End Sub
Public Sub Box(sMsg)
StartBox
BoxLine sMsg
EndBox
End Sub
'= END OF Box utility methods
'= Utility to center given text padded out to a certain width of text
'= assuming font is monospaced
Public Function Centre(sText, nWidth)
dim iLen
iLen = len(sText)
'= Check for overflow
if ilen > nwidth then Centre = sText : exit Function
'= Calculate padding either side
iLen = ( nWidth - iLen ) / 2
'= Generate text with padding
Centre = left( space(iLen) & sText & space(ilen), nWidth )
End Function
'= Method to write a line of text to the console
Public Sub Print( sText )
oOUT.WriteLine sText
End Sub
'= Method to prompt user input from the console with a message
Public Function Prompt( sText )
oOUT.Write sText
Prompt = Read()
End Function
'= Method to read input from the console with no prompting
Public Function Read()
Read = oIN.ReadLine
End Function
'= Method to provide wait for n seconds
Public Sub Wait(nSeconds)
WScript.Sleep nSeconds * 1000
End Sub
'= Method to pause for user to continue
Public Sub Pause
Prompt "Hit enter to continue..."
End Sub
END CLASS
Create a .vbs with the following code, which will open your main .vbs:
Set objShell = WScript.CreateObject("WScript.shell")
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""
Here is my main .vbs
Option Explicit
Dim i
for i = 1 To 5
Wscript.Echo i
Wscript.Sleep 5000
Next
You can run this script to echo in the command line
set wshShell = createObject("wscript.shell")
wshShell.run"cmd.exe /c echo something",1
For console output I use a snippet that quits elegantly if run in the wrong run-time. (And print is shorter to type...)
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
print "hello"

Ping script with loop and save in a txt

i try to make an Ping script with vbs. I need a Script, that ping (no ping limit, the program will run all the time) a computername in the network every 2 seconds and save the results in a txt file.
For Example:
06/08/2010 - 13:53:22 | The Computer "..." is online
06/08/2010 - 13:53:24 | The Computer "..." is offline
Now i try a little bit:
strComputer = "TestPC"
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
ExecQuery("select * from Win32_PingStatus where address = '"_
& strComputer & "'")
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) Or objStatus.StatusCode <> 0 Then
..........
Next
And than i don't know how to make it. (I'm new with vbs :-))
I hope some one can help me.
Greeting,
matthias
Try this
Option Explicit
Dim strHost, strFile
strHost = "www.google.com" '"127.0.0.1"
strFile = "C:\Test.txt"
PingForever strHost, strFile
Sub PingForever(strHost, outputfile)
Dim Output, Shell, strCommand, ReturnCode
Set Output = CreateObject("Scripting.FileSystemObject").OpenTextFile(outputfile, 8, True)
Set Shell = CreateObject("wscript.shell")
strCommand = "ping -n 1 -w 300 " & strHost
While(True)
ReturnCode = Shell.Run(strCommand, 0, True)
If ReturnCode = 0 Then
Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is online"
Else
Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is offline"
End If
Wscript.Sleep 2000
Wend
End Sub
You put your pings inside a loop of some kind and then use Wscript.Sleep 2000 to sleep for 2 seconds.
Then you use the File System Object (FSO) to write to a file. Information can be found here.
Edit: Something like this might work:
Const OpenFileForAppending = 8
Dim fso, ts
Set fso = CreateObject("Scripting. FileSystemObject")
While 1 > 0 ' loop forever
Set ts = fso.OpenTextFile("c:\temp\test.txt", OpenFileForAppending, True)
' do your pinging code
'if ok
ts.WriteLine("OK")
'else
ts.WriteLine("Not OK")
'endif
ts.Close()
Wscript.Sleep 2000
Wend

Resources