?
Solved

How can I call a script from an HTA and print the output back to the HTA?

Posted on 2008-10-22
12
Medium Priority
?
831 Views
Last Modified: 2012-05-05
I'm in process of making an HTA front end for a collection of scripts I currently manage/create.  What I'd like to do is to have the HTA take the user input required to run the script, pass those variables to the script, then print back into the HTA (in a SPAN or DIV) the output or results of the script.

I've already got the HTA to ask for user input based on what script they selected to run, AND I know how to call a script once the "submit" button has been pressed, but how do I pass the necessary variables to the script and then pull back the final output?  What code do I need to put into the script to pass the output information back to the HTA?
0
Comment
Question by:piattnd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
12 Comments
 
LVL 65

Expert Comment

by:RobSampson
ID: 22782942
Hi, here's what I think....

First off, the scripts that your HTA is calling would need to be outputting the necessary data, either to an output file or to WScript.Echo.

If they output to a file, then in the HTA you would run

objShell.Run "cscript """ & txt_script.Value & """ " & txt_param1.Value & " " & txt_param2.Value, 1, True
Set objFile = objFSO.OpenTextFile(strScriptOutput, 1, False)
span_result.InnerHTML = objFile.ReadAll
objFile.Close

but, if it outputs using WScript.Echo statements, then you could redirect that to a file, then open it...

objShell.Run "cmd /c cscript """ & txt_script.Value & """ " & txt_param1.Value & " " & txt_param2.Value & " > C:\MyOutputFile.txt", 1, True
Set objFile = objFSO.OpenTextFile("C:\MyOutputFile.txt", 1, False)
span_result.InnerHTML = objFile.ReadAll
objFile.Close

Um....is that it?  Does that help?  Let me know if I have totally confused you...

Regards,

Rob.
0
 
LVL 12

Author Comment

by:piattnd
ID: 22783173
I'll give it a shot at work tomorrow and let you know.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22783295
Oh, and when you use this to pass parameters to the script
objShell.Run "cscript """ & txt_script.Value & """ " & txt_param1.Value & " " & txt_param2.Value, 1, True

that passes values from text boxes called txt_param1 and txt_param2 respectively.

The script that gets execute must capture those parameters, using
strArg1 = WScript.Arguments.Item(0)
strArg2 = WScript.Arguments.Item(1)

Regards,

Rob.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 12

Author Comment

by:piattnd
ID: 22790211
Ok so let me just run through a scenario so atleast both you and I know that I understand you lol.

Lets say my HTA asks for the user to input 5 values.  They click the submit button and the script writes each of those values to seperate text files.  Then the HTA kicks off the vbs script that performs the work and I have the VBS file write it's output to another text file (one text file per DIV or SPAN I'm guessing).

How does the HTA know when the script has finished?  Or is that part of the whole kicking off the VBS, in other words, it sits at the line to kick off the script until the process has finished, then after that line would be the read from the output text files....

Do I make sense?  lol
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22792012
Hmmm, not exactly.....

The HTA would ask for 2 values, say from five text boxes.  A text box called txt_script has the path to the vbs file, and text boxes called txt_param1 and txt_param2 hold those values.

The submit button would call a procedure like this:

Sub Run_Script
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set objShell = CreateObject("WScript.Shell")
     strOutputfile = "C:\Temp\scriptoutput.txt"
     objShell.Run "cmd /c cscript """ & txt_script.Value & """ " & txt_param1.Value & " " & txt_param2.Value & " > " & strOutputFile, 1, True
     Set objFile = objFSO.OpenTextFile(strOutputFile, 1, False)
     span_result.InnerHTML = objFile.ReadAll
     objFile.Close
End Sub

It is the True on the end of the objShell.Run that would make the code wait until the script was finished.

Then it would read the output file that the script creates, and you'd have the info.

I'll dig up a quick demo for you....

Regards,

Rob.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22792181
OK, hopefully this suits.....this is the HTA....

This is the only bit you should have to modify:
            arrScripts = Array( _
                  "C:\Temp\Temp\Test Script\ShowLoggedOnUser.vbs|computername", _
                  "C:\Temp\Temp\Test Script\ShowIPAddresses.vbs|computername", _
                  "C:\Temp\Temp\Test Script\ShowComputerName.vbs|computername" _
            )

Where you specify the script to run, and the names of parameters separated by a pipe character.

The three sample scripts will follow.....

Regards,

Rob.
<Html>
<Head>
<Title>Test HTA</Title>
 
<HTA:Application
Caption = Yes
Border = Thin
Scroll = Yes
SingleInstance = Yes
ShowInTaskBar = Yes
MaximizeButton = Yes
MinimizeButton = Yes>
 
<script Language = VBScript>
	Sub Window_OnLoad
		intWidth = 800
		intHeight = 600
		Me.ResizeTo intWidth, intHeight
		Me.MoveTo ((Screen.Width / 2) - (intWidth / 2)),((Screen.Height / 2) - (intHeight / 2))
		arrScripts = Array( _
			"C:\Temp\Temp\Test Script\ShowLoggedOnUser.vbs|computername", _
			"C:\Temp\Temp\Test Script\ShowIPAddresses.vbs|computername", _
			"C:\Temp\Temp\Test Script\ShowComputerName.vbs|computername" _
		)
		For intOption = LBound(arrScripts) To UBound(arrScripts)
			If InStr(arrScripts(intOption), "|") > 0 Then
				strText = Left(arrScripts(intOption), InStr(arrScripts(intOption), "|") - 1)
			Else
				strText = arrScripts(intOption)
			End If
			Set objSelectOption = Document.CreateElement("OPTION")
			objSelectOption.Text = strText
			objSelectOption.Value = arrScripts(intOption)
			opt_script.Add objSelectOption
		Next
		Update_Parameters
	End Sub
 
	Sub Default_Buttons
		If Window.Event.KeyCode = 13 Then
			btn_run.Click
		End If
	End Sub
 
	Sub Update_Parameters
		strParameters = "<table><tr>"
		If InStr(opt_script.Value, "|") > 0 Then
			arrParameters = Split(Mid(opt_script.Value, InStr(opt_script.Value, "|") + 1), "|")
			For Each strParam In arrParameters
				strParameters = strParameters & VbCrLf & "<tr><td>" & strParam & ":</td><td><input type='text' id='txt_" & strParam & "' name='txt_" & strParam & "' size='50'></tr>"
			Next
		Else
			strParameters = strParameters & "<td></td><td></td>"
		End If
		strParameters = strParameters & "</table>"
		span_parameters.innerHTML = strParameters
	End Sub
	
	Sub Run_Script
		Set objFSO = CreateObject("Scripting.FileSystemObject")
		Set objShell = CreateObject("WScript.Shell")
		strParameters = ""
		If InStr(opt_script.Value, "|") > 0 Then
			strFileName = Left(opt_script.Value, InStr(opt_script.Value, "|") - 1)
			arrParameters = Split(Mid(opt_script.Value, InStr(opt_script.Value, "|") + 1), "|")
			For Each strParam In arrParameters
				strParameters = strParameters & " """ & Eval("txt_" & strParam & ".Value") & """"
			Next
		Else
			strFileName = opt_script.Value
			strParameters = ""
		End If
		strVBSPath = objFSO.GetFile(strFileName).ShortPath & strParameters
		strTempFile = "C:\Temp\ScriptOutput.txt"
		objShell.Run "cmd /c cscript.exe " & strVBSPath & " > """ & strTempFile & """", 0, True
		Set objFile = objFSO.OpenTextFile(strTempFile, 1, False)
		span_results.InnerHTML = Replace(objFile.ReadAll, VbCrLf, "<BR>")
		objFile.Close
		Set objFile = Nothing
	End Sub
</script>
<body style="background-color:#B0C4DE;" onkeypress='vbs:Default_Buttons'>
	<table height="90%" width width= "90%" border="0" align="center">
		<tr>
			<td align="center" colspan="2">
				<h2>Run Script From HTA</h2>
			</td>
		</tr>
		<tr>
			<td>
				Select script to run:
			</td>
			<td>
				<select id="opt_script" name="opt_script" size="1" onChange="vbs:Update_Parameters">
				</select>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<span id="span_parameters"></span>
			</td>
		</tr>
		<tr align="center">
			<td colspan="2">
				<button name="btn_run" id="btn_run" accessKey="R" onclick="vbs:Run_Script"><u>R</u>un Script</button>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<b>Results:</b><br>
				<span id="span_results"></span>
			</td>
		</tr>
	</table>
</body>
</head>
</html>

Open in new window

0
 
LVL 65

Accepted Solution

by:
RobSampson earned 2000 total points
ID: 22792202
Here's the three test scripts I used....

Regards,

Rob.
'==========================================================================
'==========================================================================
'                    SHOWLOGGEDONUSER.VBS
'
If WScript.Arguments.Count > 0 Then
	strComputer = WScript.Arguments.Item(0)
Else
	strComputer = InputBox("Please enter a computer name:", "Computer Name")
End If
Set objWMIService = GetObject("winmgmts:" _
   	& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colComputer = objWMIService.ExecQuery _
   	("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
    strUserName = "User Name: " & objComputer.UserName
    strHostName = "Host Name: " & objComputer.Name
Next
WScript.Echo strUserName & VbCrLf & strPassword
'
'==========================================================================
'==========================================================================
'==========================================================================
'==========================================================================
'                    SHOWIPADDRESSES.VBS
'
If WScript.Arguments.Count > 0 Then
	strComputer = WScript.Arguments.Item(0)
Else
	strComputer = InputBox("Please enter a computer name:", "Computer Name")
End If
Set objWMIService = GetObject("winmgmts:" _
   	& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colComputerIP = objWMIService.ExecQuery _
   	("Select * from Win32_NetworkAdapterConfiguration")
For Each IPConfig in colComputerIP
	If Not IsNull(IPConfig.IPAddress) Then 
		'strIPAddress = strIPAddress & IPConfig.Description & ": "
        For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)
			'strIPAddress = strIPAddress & "IP Address: " & IPConfig.IPAddress(intIPCount) & "~"
			strIPAddress = strIPAddress & IPConfig.Description & ": " & IPConfig.IPAddress(intIPCount) & "~"
		Next
	End If
Next
 
If Right(strIPAddress, 1) = "~" Then
	strIPAddress = Left(strIPAddress, Len(strIPAddress) - 1)
End If
strIPAddress = Replace(strIPAddress, "~", vbCrLf)
 
Wscript.Echo strIPAddress
'
'==========================================================================
'==========================================================================
'==========================================================================
'==========================================================================
'                    SHOWCOMPUTERNAME.VBS
'
If WScript.Arguments.Count > 0 Then
	strComputer = WScript.Arguments.Item(0)
Else
	strComputer = InputBox("Please enter a computer name:", "Computer Name")
End If
Set objWMIService = GetObject("winmgmts:" _
   	& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
   Set colSystemInfo = objWMIService.ExecQuery _
   	("Select * from Win32_OperatingSystem",,48)
For Each objItem in colSystemInfo
     strOS_Caption = "Caption: " & objItem.Caption
     strOS_SPVersion = "SP Version: " & objItem.CSDVersion
     strOS_VerNumber = "Version Number: " & objItem.Version
Next
WScript.Echo strOS_Caption & VbCrLf & strOS_SPVersion & VbCrLf & strOS_VerNumber
'
'==========================================================================
'==========================================================================

Open in new window

0
 
LVL 12

Author Comment

by:piattnd
ID: 22792655
Awesome, I'll look over these tomorrow when I get into work!
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22792914
No problem...I hope they make sense...

Rob.
0
 
LVL 12

Author Comment

by:piattnd
ID: 22800773
I won't get to test this until Monday, I've had a few projects thrown on my I had to get done before the weekend.  I'll hopefully be able to accept your solution on monday!  :D
0
 
LVL 12

Author Closing Comment

by:piattnd
ID: 31508839
Thank you Rob!  I think that's the second time you've come through for me.... :D
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 22837106
Thanks for the grade.  Glad to help.

Regards,

Rob.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question