I need help using VBScript to control a commandline program - windows

Using a VBScript (just an example) something like
result = MsgBox ("Would you like to install the AntrixAPI?", vbYesNo, "Installing AntrixAPI")
Select Case result
Case vbYes
MsgBox("The API will be installed.")
Case vbNo
MsgBox("The API will not be install.")
End Select
How could I use this to control a commandline program. Let's say the user selected yes. Then the command would go to a certain point only if the user selected yes.
(example command)
#echo off
:UserSelectedYes
REM This is where the prompt would go if the user selected yes
wget http://www.example.com/thisisafakedomain/api/antrix
:UserSelectedNo
REM This is where the prompt would go if the user selected no
end
Would this be possible?

You can create a MS-DOS process and execute every script, you want!
Just like this:
Dim oProcess As New Process
With (oProcess.StartInfo)
.Arguments = "/k <command> & <command> & <command> & exit"
.FileName = "cmd.exe"
.WindowStyle = ProcessWindowStyle.Hidden
.CreateNoWindow = True
End With
oProcess.Start()
It is not the best and genteelst way, but the fastest.
I do not know exactly, if this is what you wanted. So feel free to redefine your question, it was not very clear what you were asking for!

This is how to download a file in vbscript.
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.pepperresources.org/LinkClick.aspx?fileticket=B1doLYYSaeY=&tabid=61", False
'This is IE 8 headers
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\test.txt", 2

Your VBScript can be as simple as this:
WScript.Quit MsgBox("Would you like to install the AntrixAPI?", vbYesNo, "Installing AntrixAPI")
Call it from your batch file and test the return value. vbYes has a value of 6, vbNo has a value of 7.
#echo off
cscript c:\test.vbs
if %errorlevel%==6 goto UserSelectedYes
if %errorlevel%==7 goto UserSelectedNo

Related

Script to display a pop-up and then kills a windows process

I'm trying to deploy an application through SCCM 2012 for Windows7 (x86 and x64) that requires to notify the user that his Microsoft Outlook should be closed before to continue with the installation. It could be either with a Timer or a (Yes / No) choice, then if the user press Yes then it will close Outlook and will continue with the installation otherwise it will send a log file saying the the user cancelled the installation but it can be retried at any time.
So far I just have the installation script that works only to install the applications using a command line script. So, it will just execute some MSI's installations and Windows updates, and then it quits.
The script I have that creates the pop up and that can be called by my CMD file is the following VBScript and was taken from a TechNet article.
Const TIMEOUT = 7
Set objShell = WScript.CreateObject("WScript.Shell")
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
strPath = Wscript.FullName
strFileVersion = objFS.GetFileVersion(strPath)
iRetVal = objShell.Popup(Wscript.FullName & vbCrLf & _
"File Version: " & _
strFileVersion & vbCrLf & _
"Would you like to close Outlook application and continue with the installation?" _
,TIMEOUT,"Outlook Validation",vbYesNo + vbQuestion)
Select Case iRetVal
Case vbYes
Set objFile = objFS.GetFile(strPath)
objShell.Popup WScript.FullName & vbCrLf & vbCrLf & _
"File Version: " & strFileVersion & vbCrLf & _
"File Size: " & Round((objFile.Size/1024),2) & _
" KB" & vbCrLf & _
"Date Created: " & objFile.DateCreated & vbCrLf & _
"Date Last Modified: " & objFile.DateLastModified & _
vbCrLf,TIMEOUT
Wscript.Quit
Case vbNo
Wscript.Quit
Case -1
WScript.StdOut.WriteLine "Popup timed out."
Wscript.Quit
End Select
So I don't know if there's any useful example that I can use and customize it from there. I'm clueless, blindfolded, I don't see the light. Well you understand my frustration.
Any ideas, examples or links will be really appreciated!!
Thanks & kind regards.
Joel.
This is one way.
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.name & " " & objItem.CommandLine
If LCase(objItem.name) = "outlook.exe" then
If Msgbox("Close Outlook", 33, "Install") = 1 then
objItem.terminate
End If
End If
Next
VBScript's Help file - https://www.microsoft.com/en-au/download/details.aspx?id=2764
For help with the WMI object use wmic at the command prompt.
wmic process get /? (same as wmic path win32_process get /?) and wmic process call /? list properties and methods.
Here my procedure which closes outlook before modifying the profile.
Is is part of a logon script. The show is a logging and informing procedure.
sub CloseOutlook
on error resume next 'to be able to log and continue
dim objWMIService, colProcessList, objProcess, sResult, oShell
set oShell = WScript.CreateObject("WScript.Shell")
set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'OUTLOOK.EXE'")
for Each objProcess in colProcessList
show "outlook is being closed"
objProcess.Terminate()
if Err <> 0 then
show "Error while closing outlook: " & err.Description
end if
sResult = oShell.Popup("Outlook is being closed, profile is configured")
next
end sub
If you want confirmation from the user you will have to use a MsgBox instead.
I'd recommend not faffing about with warnings and closing Outlook, but instead configure the advert to run when no users are logged in. Less chance for problems or accidentally miss-clicked "oh no you lost my emails" situations.

Vbscript msxml12.XMLHTTP error handling

I use this vbscript code, to download web page:
Dim oXML
Set oXML = CreateObject("msxm12.XMLHTTP")
oXML.Open "GET", "mysite.com", False
oXML.Send
If there is no such web site, I get an error 80004005, Unspecified error at line "oXML.Open ..."
How can I handle this error in vbscript? I want to catch this error and show msgbox with my error, i.e. web page is not available.
There are at least three possible points of failure in your script.
CreateObject may fail; e.g. if you use msxml12 (digit 1) instead of msxml2 (letter l). Such blunders should be fixed during development.
.Open may fail; e.g. if you use "mysite.com" instead of a syntactically correct URL. If you get the URL at runtime, a 'look before you jump' check is advisable, an OERN can be used to catch bad URLs not found by your validation.
.Send may fail; e.g. if the site is down or abandoned. This is a clear case for an OERN.
The most important rule wrt OERN: Keep it local and short (Only one risky line between OERN and OEG0).
Demo code:
Option Explicit
Dim sUrl
For Each sUrl In Split("http://stackoverflow.com http://pipapo.org mysite.com")
Dim oXML, aErr
' Set oXML = CreateObject("msxm12.XMLHTTP")
Set oXML = CreateObject("msxml2.XMLHTTP.6.0")
On Error Resume Next
oXML.Open "GET", sUrl, False
aErr = Array(Err.Number, Err.Description)
On Error GoTo 0
If 0 = aErr(0) Then
On Error Resume Next
oXML.Send
aErr = Array(Err.Number, Err.Description)
On Error GoTo 0
Select Case True
Case 0 <> aErr(0)
WScript.Echo "send failed:", aErr(0), aErr(1)
Case 200 = oXML.status
WScript.Echo sUrl, oXML.status, oXML.statusText
Case Else
WScript.Echo "further work needed:"
WScript.Echo sUrl, oXML.status, oXML.statusText
End Select
Else
WScript.Echo "open failed:", aErr(0), aErr(1)
End If
Next
output:
cscript 24863986.vbs
http://stackoverflow.com 200 OK
send failed: -2146697211 The system cannot locate the resource specified.
open failed: -2147012890 System error: -2147012890.
But your problem is it's msxml2.http (El 2) not msxm12.http (1 2). Yopur error is because you dd not create the object sucessfully or test the object isn't empty.
The URL has to be 100% correct. Unlike a browser there is no code to fix urls.
The purpose of my program is to get error details.
How I get a correct URL is to type my url in a browser, navigate, and the correct URL is often in the address bar. The other way is to use Properties of a link etc to get the URL.
Also Microsoft.XMLHTTP maps to Microsoft.XMLHTTP.1.0. HKEY_CLASSES_ROOT\Msxml2.XMLHTTP maps to Msxml2.XMLHTTP.3.0. Try a later one
Try this way using xmlhttp. Edit the url's etc. If it seems to work comment out the if / end if to dump info even if seeming to work. It's vbscript but vbscript works in vb6.
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com/en-au/default.aspx", False
'This is IE 8 headers
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\test.txt", 2
Also see if these other objects work.
C:\Users>reg query hkcr /f xmlhttp
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP.1.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.6.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.6.0
End of search: 12 match(es) found.
Also be aware there is a limit on how many times you can call any particular XMLHTTP object before a lockout occurs. If that happens, and it does when debugging code, just change to a different xmlhttp object

Can't retrieve Web page via VBScript unless opened in browser first

I want to retrieve and process some Web pages with VBScript, which is being run from the command line. It bears mentioning that I'm on a work computer, and "some setting are managed by your system administrator". Also, I log in to the computer with a CAC, so (and I think this is the problem) there are certificates involved.
My problem is that, frequently, when I run the VBScript I'll get back a 401/unauthorized error, for both HTTPS and non-HTTPS sites. If I then open the URL in a browser, the script (still being run from the command line) will work. If I run the script on my home computer I can always access any URL without first having to open it in a browser. So, I'm guessing it has to do with either the certificates in my CAC (which are also installed on the computer), or some other certificate on the computer, that are used to authenticate the connection (or some such thing).
My question is: how can I retrieve various Web pages using VBScript (without installing any additional software) without having to first open the URL in a browser to get the script to work?
Here is my code for getting a Web page, if that helps:
function getWebPage(sURL)
dim iErrorCount
on error resume next
'******************
'ERROR CHECKING OFF
'******************
oHTTP.Open "GET", sURL, False
oHTTP.Send
if (err.number <> 0) then
iErrorCount = 0
do
iErrorCount = iErrorCount + 1
log "log.txt", "Error retrieving Web page. Error #0x" & hex(err.number) & ". Description: " & err.description, 0, true
if (iErrorCount = 5) then
log "log.txt", vbTab & "Five successive errors retrieving Web page. Exiting...", 1, true
msgbox "ERROR: Five successive errors retrieving " & chr(34) & sURL & chr(34) & vbCRLF & vbCRLF & "See the log file for details." & vbCRLF & vbCRLF & "Exiting...", vbOkOnly, programName
log "last result.html", oHTTP.ResponseText, 0, false
wscript.quit
else
wscript.sleep iErrorCount * 60000
set oHTTP = nothing
set oHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
oHTTP.Open "GET", sURL, False
oHTTP.Send
end if
loop until (err.number = 0)
end if
on error goto 0
'*****************
'ERROR CHECKING ON
'*****************
if (oHTTP.Status <> 200) then
log "log.txt", vbcrlf & vbtab & "Error retrieving Web page" & vbcrlf & vbtab & "URL: " & sURL & vbcrlf & vbtab & "Status: " & oHTTP.Status & vbcrlf & vbtab & "Description: " & oHTTP.statusText, 1, true
msgbox "ERROR: Cannot retrieve Web page." & vbCRLF & vbCRLF & "See the log file for details." & vbCRLF & vbCRLF & "Exiting...", vbOkOnly, programName
wscript.quit
else
' log "last result.html", oHTTP.ResponseText, 0, false
getWebPage = oHTTP.ResponseText
end if
end function
Any thoughts?
You have to get the url exactly right with xmlhttp object. Run this code and print out the error messages (you can copy a messagebox with Ctrl + C).
Set fso = CreateObject("Scripting.FileSystemObject")
Set Outp = Wscript.Stdout
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "ftp://ftp.microsoft.com/Softlib/README.TXT", False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\safetyscanner.exe", 2

How to POST data to Google Analytics with VB6

We have an ancient VB6 component that needs Google Analytics tracking. I am using the Internet Transfer Control to POST data via HTTP. I cannot see my tracking data in the Google Analytics reports. This leads me to believe that I cam calling POST incorrectly.
I have already added Google Analytics tracking to a desktop .Net Application and can see that data so I know it works.
I have a VB6 form with a button on it. The button-click event executes:
Dim var1 As String
var1 = "v=1&tid=UA-00000000-1&cid=123&t=appview&cd=VBScreen"
Inet1.Execute "http://www.google-analytics.com/collect", "POST", var1
This doesn't return an error but no data can be seen in the Google Analytics reporting pages. What am I going wrong?
I do not need to use the Internet Transfer Control if there is some other simple way to do this.
After Execute() is called, Inet1_StateChanged is fired and the state is icResponseCompleted. Inet1.ResponseInfo == "" and Inet1.StillExecuting == False.
Try this way using xmlhttp. Edit the url's etc. If it seems to work comment out the if / end if to dump info even if seeming to work. It's vbscript but vbscript works in vb6.
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com/en-au/default.aspx", False
'This is IE 8 headers
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\test.txt", 2
I don't recall why the original code did not work, but I was able to get it working with the following code:
Dim xmlhttp As WinHttp.WinHttpRequest
Set xmlhttp = New WinHttp.WinHttpRequest
Dim var1 As String
var1 = "v=1&tid=UA-00000000-0&cid=123&an=MyAN&av=1.0&t=event&ec=ecData&ea=eaData&el=elData"
xmlhttp.Open "POST", "http://www.google-analytics.com/collect", False
xmlhttp.send var1

How to find operating system name without using WMI in VBScript?

I need a way to find the operating system version without using winmgmts. I need a platform independent way of find the name of the OS, vista, win7, etc.
We have to parse paths in user accounts that are different on 2K/XP then they are on Vista / Win7. The comspec return looks like this: Microsoft Windows [Version 6.1.7600]. 2k/XP is Version 5.x and Vista/Win7 is Version 6.x.
Set shell = CreateObject("WScript.Shell")
Set getOSVersion = shell.exec("%comspec% /c ver")
version = getOSVersion.stdout.readall
wscript.echo version
Select Case True
Case InStr(version, "n 5.") > 1 : GetOS = "XP"
Case InStr(version, "n 6.") > 1 : GetOS = "Vista"
Case Else : GetOS = "Unknown"
End Select
wscript.echo GetOS`
VBscript:
Set oShell = CreateObject( "WScript.Shell" )
os_name=oShell.ExpandEnvironmentStrings("%OS%")
WScript.Echo os_name
This page provides several wrapper routines for obtaining general Windows operation system information, all using a single call to the GetVersionEx API.
From VisualBasicScript.com:
Option Explicit
Dim oShell
Dim oShellExec, oStdOutputText, sText, iElement, aOS, sOS
Set oShell = CreateObject("Wscript.Shell")
Set oShellExec = oShell.Exec("%comspec% /c ver")
Set oStdOutputText = oShellExec.StdOut
Do While Not oStdOutputText.AtEndOfStream
sText = oStdOutputText.ReadLine
aOS = Array("Windows 95", "Windows 98", "Windows NT", "Windows 2000", "Windows XP", "Microsoft Windows [Version")
For iElement = LBound(aOS) To UBound(aOS)
If InStr(sText, aOS(iElement)) <> 0 Then
If aOS(iElement) = "Microsoft Windows [Version" Then
If InStr(sText, "Version6.0") <> 0 Then
sOS = "Windows Vista"
ElseIf InStr(sText, "Version 6.1")<>0 Then
sOS = "Windows 7"
Else
sOS = "Windows 2003"
End If
Else
sOS = aOS(iElement)
End If
End If
Next
Loop
WScript.Echo sOS
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set oss = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each os in oss
Wscript.Echo "Caption: " & os.Caption
Wscript.Echo "Code Set: " & os.CodeSet
Wscript.Echo "Country Code: " & os.CountryCode
Wscript.Echo "Debug: " & os.Debug
Wscript.Echo "Encryption Level: " & os.EncryptionLevel
dtmConvertedDate.Value = os.InstallDate
dtmInstallDate = dtmConvertedDate.GetVarDate
Wscript.Echo "Install Date: " & dtmInstallDate
Wscript.Echo "Licensed Users: " & os.NumberOfLicensedUsers
Wscript.Echo "Organization: " & os.Organization
Wscript.Echo "OS Language: " & os.OSLanguage
Wscript.Echo "OS Product Suite: " & os.OSProductSuite
Wscript.Echo "OS Type: " & os.OSType
Wscript.Echo "Primary: " & os.Primary
Wscript.Echo "Serial Number: " & os.SerialNumber
Wscript.Echo "Version: " & os.Version
Next

Resources