Windows shell script not able to make existing IE window visible? - windows

I have been trying to create a really simple script to maintain visibility on an IE page but am currently unable to force the visibility or foreground position of an existing IE window.
I am able to successfully activate the window using WshShell.AppActivate() but it does not make the page foreground to a user. A sample from my code is below.
Basically the code loops until the user ends the notepad window. my confusion is specifically with why IE is not visible no matter what commands I send
Dim pressX
Dim FindProc
pressX = 1
' Create WScript Shell Object to access filesystem.
Set WshShell = WScript.CreateObject("WScript.Shell")
'WshShell.Run "NoScreenSaver.txt", 2, 0
' Define Which process to seek for to terminate script
strComputer = "."
FindProc = "NoScreenSaver"
Dim objApp : Set objApp = CreateObject("Shell.Application")
Dim IE : Set IE = Nothing
Dim objWindow
' Loop start
Do
' Wait for 5 minutes
WScript.Sleep 3000 '000
For Each objWindow In objApp.Windows
If (InStr(objWindow.Name, "Internet Explorer")) Then
Set IE = objWindow
Exit For
End If
Next
' check if specific notepad closed
If WshShell.AppActivate("NoScreenSaver.txt") = True Then
'WshShell.AppActivate("iexplore.exe")
'wscript.echo FindProc & " is running"
Else
wscript.echo FindProc & " is not running" & vbCrLf & "Script will now end"
pressX = 0
End If
IE.visible = True
wshshell.appactivate ie.name
IE.navigate "google.ca"
' Send dummy key
WshShell.SendKeys "{F13}"
' repeat
Loop While pressX
I never wanted to use AppActivate to check for the specific notepad window either since it would take foreground. There is some information regarding using a COM wrapper but the COM wrapper approach is not possible within my constraints.

Related

Use VBS to run PowerShell

So I have a .ps1 file which creates a form.
That Form takes 10-20secs depending on PCs performance and connection on first load.
Now I am currently using VBS to load a simple .gif file as a loading screen concurrently running the .ps1 file right after.
My issue at the moment is that, I want to close the loading screen when the form pops up. I tried to determine via processes but that failed because of the it loads powershell.exe but the form takes 10sec...
Is it this possible?
Of have you guys got a better idea to do this?
Dim i
Dim strComputer
Dim FindProc
Dim counter
counter = 0
strComputer = "."
FindProc = "powershell.exe"
'Load the gif file
Set objExplorer = CreateObject("InternetExplorer.Application")
With objExplorer
.Navigate "about:blank"
.Visible = 1
.Document.Title = "Show Image"
.Toolbar=False
.Statusbar=False
.Top=400
.Left=400
.Height=355
.Width=435
.Document.Body.InnerHTML = "<img src='\\10.10.67.173\Templates$\Scripts\Resources\loadingtest.gif'>"
End With
'Run the PS script
Set objShell = CreateObject("Wscript.shell")
objShell.Run "CMD /C START /B " & objShell.ExpandEnvironmentStrings("%SystemRoot%") & "\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -file \\10.10.67.173\Templates$\Scripts\FormSignature-V0.9.5.ps1", 0, False
'Determine when to close Loading screen
Do While counter < 3
wscript.Sleep 2000
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select Name from Win32_Process WHERE Name LIKE '" & FindProc & "%'")
If colProcessList.count>0 then
'Quit the process if it finds its running
WScript.Echo("found")
'objExplorer.quit
else
'Do nothing
WScript.Echo("not found")
End if
Set objWMIService = Nothing
Set colProcessList = Nothing
counter = counter + 1
Loop
Set objShell = Nothing
In your VB script:
Create a file in an folder the PS script can access.
Launch your loading image.
Launch your PS script.
In your wait loop, every second or so, check if the file still exists.
If it does, close the instance of IE and exit your script.
In your PS script:
After your form initialization code is finished or the first action after the form load, locate and delete the file.

How to click on ok button in message box using vbscript

I have written a simple script to press ok on message box but its not working. Please help me how to do this
here is the sample code
set oWShell = createobject("WScript.Shell")
MsgBox "Hello"
WScript.Sleep 2000
oWShell.Sendkeys "{enter}"
MsgBox waits for the click. If you don't click yourself, it gets never to "Sleep" or "SendKeys".
I assume you are just trying to learn, because this code makes no sense. If you want to press a button on another programs window, this could work. But in its own process this doesn't work.
If you really want to click your own MsgBox, you have to do it with a separate script. One creates the MsgBox and another clicks the button.
If you just want to close a message box after a certain period of time, check out the Popup() method of the WshShell class. Its second parameter specifies the number of seconds to display the message box for before closing it.
With CreateObject("WScript.Shell")
' Display a message box that disappears after two seconds...
.Popup "Hello", 2
End With
chek this site
you need this:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText, 51, "Warning......!"
how to click on button in message box and control of display time here the script can do that .
just copy this lines of code and paste in text file then save it as "ControlMsgBox.vbs".
''' IN THE NAME OF ALLAH
' THIS SCRIPT CONTROL OF MSGBOX DISPLAY TIME
' LET SENKEYS DEAL WITH THE MSGBOX
' SOLVE THE PROBLEM OF APPACTIVATE NOT WORKING EFFECTIVE
On Error Resume Next
Dim Sh : Set Sh=CreateObject("wscript.shell") ' declare and create the wshshell
Dim path : path =Replace(WScript.ScriptFullName,WScript.ScriptName,"") 'declare the variable of the current script path
Dim myMessage : myMessage="This is my message ." 'declare variable of the of the display text of msgbox
Sh.run "cmd.exe /c cd """&path&""" && echo msgbox """&myMessage&""",,""hello"" > mymsgbox.vbs",0,false 'create masgbox script in the same path
WScript.Sleep 1000 'wait 1 sec to let process of create msgbox script execute
Sh.run "mymsgbox.vbs" 'run the created msgbox script
WScript.Sleep 3000 ' let the msgbox display for 3 sec before we sendkeys to close
For i=0 To 600 ' loop to retry select correct msgbox window about 1 min
ret = Sh.AppActivate("In_The_Name_Of_Allah") 'select the activate msgbox window (if this loop 300 this mean loop will continue 30 sec if 600 (1 min)
If ret = True Then ' check if the msgbox windows select or not
Sh.SendKeys "%N" 'send key of Alt+N to select first button in msgbox (ok)
End If
ret = Sh.AppActivate("In_The_Name_Of_Allah") 'recheck again to be sure that we will not send key out of target windows (msgbox window)
If ret = True Then
Sh.SendKeys "{enter}" ' send key to click enter
wscript.sleep 500
ret=Sh.AppActivate("In_The_Name_Of_Allah")
If ret=False Then ' using nested IF to sure of selected windows is false because its close
Exit For ' exit for loop directly and execute what after for next
End If
End If
WScript.Sleep 100
Next
With CreateObject("Scripting.FileSystemObject")
If .FileExists(path&"mymsgbox.vbs") Then 'check if the msgbox script we create form this script exist or not
.DeleteFile(path&"mymsgbox.vbs") 'delete the msgbox script we create after message window closed
End If
End With
Set Sh=Nothing 'remove the sh object create
WScript.Quit ' terminate wscript.exe instance who run this script

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

VBScript to Display Countdown using Vbscript Graphical Elements

I wanted to display a MessageBox which displays countdown from 10 to 1 and autocloses after 10 seconds. As Msgbox in vbscript passes code execution untill the user acts on it i tried it using Popup in Wscript Shell Object
Dim counter
Dim oShell
counter = 10
Set oShell= CreateObject("Wscript.Shell")
While counter > 0
oShell.Popup " Left " & counter & " Seconds",1,"Remind"
counter = counter-1
Wend
But it auto-closes for every second and opens a new popup is there any way i can display the countdown and autoclose using the available GUI elements in vb script
Afraid not, the popup is modal & can't be interacted with while its displayed so there is no way to update its existing content.
If you want a more flexible UI you will need to use something different, the console or HTML in an HTA.
You can use Internet Explorer to create a non-modal display.
Set oIE = CreateObject("InternetExplorer.Application")
With oIE
.navigate("about:blank")
.Document.Title = "Countdown" & string(100, chrb(160))
.resizable=0
.height=200
.width=100
.menubar=0
.toolbar=0
.statusBar=0
.visible=1
End With
' wait for page to load
Do while oIE.Busy
wscript.sleep 500
Loop
' prepare document body
oIE.document.body.innerHTML = "<div id=""countdown"" style=""font: 36pt sans-serif;text-align:center;""></div>"
' display the countdown
for i=10 to 0 step -1
oIE.document.all.countdown.innerText= i
wscript.sleep 1000
next
oIE.quit
I have a code, but it might not help
dTimer=InputBox("Enter timer interval in minutes","Set Timer") 'minutes
do until IsNumeric(dTimer)=True
dTimer=InputBox("Invalid Entry" & vbnewline & vbnewline & _
"Enter timer interval in minutes","Set Timer") 'minutes
loop
flop=InputBox("What do you want to set the timer for?")
if dTimer<>"" then
do
WScript.Sleep dTimer*60*1000 'convert from minutes to milliseconds
Set Sapi = Wscript.CreateObject("SAPI.spVoice")
Sapi.speak "Time's up."
t=MsgBox(flop & vbnewline & vbnewline & "Restart Timer?", _
vbYesNo, "It's been " & dTimer &" minute(s)")
if t=6 then 'if yes
'continue loop
else 'exit loop
exit do
end if
loop
end if
please excuse my weird variable names.
This code is from https://wellsr.com/vba/2015/vbscript/vbscript-timer-with-wscript-sleep/
It actually is possible to edit the countdown, very easily for VBScript, so I don't understand what the problem is.
Here's the code:
Dim counter
Dim oShell
counter =InputBox("")
#if you add =InputBox you can have the choice to type in the amount of times the popup repeats#
Set oShell= CreateObject("Wscript.Shell")
While counter > 0
oShell.Popup " Time until shutdown " & counter & " Seconds",(1),"[3]Critical Viruses Detected
#and if you change the (1) to whatever number you want then you can change how fast the popup repeats and if you join this with the "open command" then you can make a gnarly nondangerous virus#
counter = counter-1
Wend

Use clipboard from VBScript

I am looking for a method to place some text onto the clipboard with VBScript. The VBScript in question will be deployed as part of our login script. I would like to avoid using anything that isn't available on a clean Windows XP system.
Edit:
In answer to the questions about what this is for.
We wanted to encourage users inside our organization to use the file server to transfer documents instead of constantly sending attachments by email. One of the biggest barriers to this is that it isn't always obvious to people what the correct network path is to a file/folder. We developed a quick script, and attached it to the Windows context menu so that a user can right click on any file/folder, and get a URL that they can email to someone within our organization.
I want the URL displayed in the dialog box to also be placed onto the clipboard.
GetNetworkPath
Another solution I have found that isn't perfect in my opinion, but doesn't have the annoying security warnings is to use clip.exe from a w2k3 server.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo hello world | clip", 0, TRUE
Example with a multiline string as per question below :
Link1
Dim string
String = "text here" &chr(13)& "more text here"
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo " & String & " | clip", 0, TRUE
Using Microsoft's clip.exe is the closest to having a clean Windows XP system solution. However you don't have to call CMD.EXE to host it in order to use it. You can call it directly and write to its input stream in your script code. Once you close the input stream clip.exe will write the contents straight to the clipboard.
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine "Something One"
oIn.WriteLine "Something Two"
oIn.WriteLine "Something Three"
oIn.Close
If you need to wait for clip to be finished before your script can continue processing then add
' loop until we're finished working.
Do While oExec.Status = 0
WScript.Sleep 100
Loop
And don't forget to release your objects
Set oIn = Nothing
Set oExec = Nothing
The closest solution I have found so far is a method to use IE to get and set stuff on the clipboard. The problem with this solution is the user gets security warnings. I am tempted to move 'about:blank' to the local computer security zone so I don't get the warnings, but I am not sure what the security implications of that would be.
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate("about:blank")
objIE.document.parentwindow.clipboardData.SetData "text", "Hello This Is A Test"
objIE.Quit
http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1215.mspx
No security warnings, full let and get access:
'create a clipboard thing
Dim ClipBoard
Set Clipboard = New cClipBoard
ClipBoard.Clear
ClipBoard.Data = "Test"
Class cClipBoard
Private objHTML
Private Sub Class_Initialize
Set objHTML = CreateObject("htmlfile")
End Sub
Public Sub Clear()
objHTML.ParentWindow.ClipboardData.ClearData()
End Sub
Public Property Let Data(Value)
objHTML.ParentWindow.ClipboardData.SetData "Text" , Value
End Property
Public Property Get Data()
Data = objHTML.ParentWindow.ClipboardData.GetData("Text")
End Property
Private Sub Class_Terminate
Set objHTML = Nothing
End Sub
End Class
Example Usage.
' Create scripting object
Dim WShell, lRunUninstall
Set WShell = CreateObject("WScript.Shell")
WShell.sendkeys "^c"
WScript.Sleep 250
bWindowFound = WShell.AppActivate("Microsoft Excel")
WShell.sendkeys ClipBoard.Data
To avoid the security warnings associated with Internet Explorer and clipboard access, I would recommend you use the Word application object and its methods to put your data onto the clipboard. Of course you can only use this on a machine that has MS Word installed, but these days that's most of them. (*In spite of the fact that you asked for stuff on a 'clean' system :) *)
' Set what you want to put in the clipboard '
strMessage = "Imagine that, it works!"
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")
' Using the object '
With objWord
.Visible = False ' Don't show word '
.Documents.Add ' Create a document '
.Selection.TypeText strMessage ' Put text into it '
.Selection.WholeStory ' Select everything in the doc '
.Selection.Copy ' Copy contents to clipboard '
.Quit False ' Close Word, don't save '
End With
You can find detail on the MS Word application object and its methods here: http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx
Microsoft doesn't give a way for VBScript to directly access the clipboard. If you do a search for 'clipboard'on this site you'll see:
Although Visual Basic for Applications supports the Screen, Printer, App, Debug, Err, and Clipboard objects, VBScript supports only the Err object. Therefore, VBScript does not allow you to access such useful objects as the mouse pointer or the clipboard. You can, however, use the Err object to provide runtime error handling for your applications.
So using notepad indirectly is probably about the best you'll be able to do with just VBScript.
Here's another version of using the "clip" command, which avoids adding a carriage return, line feed to the end of the string:
strA= "some character string"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /C echo . | set /p x=" & strA & "| c:\clip.exe", 2
s = "String: """ & strA & """ is on the clipboard."
Wscript.Echo s
I've only tested this in XP. clip.exe was downloaded from Link and placed in C:\.
I've found a way to copy multi line information to clipboard by vbscript/cmd.
Sequence:
with VBS generate the final "formatted string" that you need copy to clipboard
generate a (txt) file with the "formatted string"
use type command from cmd to paste information to clip by pipe
Example script:
Function CopyToClipboard( sInputString )
Dim oShell: Set oShell = CreateObject("WScript.Shell")
Dim sTempFolder: sTempFolder = oShell.ExpandEnvironmentStrings("%TEMP%")
Dim sFullFilePath: sFullFilePath = sTempFolder & "\" & "temp_file.txt"
Const iForWriting = 2, bCreateFile = True
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
With oFSO.OpenTextFile(sFullFilePath, iForWriting, bCreateFile)
.Write sInputString
.Close
End With
Const iHideWindow = 0, bWaitOnReturnTrue = True
Dim sCommand: sCommand = "CMD /C TYPE " & sFullFilePath & "|CLIP"
oShell.Run sCommand, iHideWindow, bWaitOnReturnTrue
Set oShell = Nothing
Set oFSO = Nothing
End Function
Sub Main
Call CopyToClipboard( "Text1" & vbNewLine & "Text2" )
End Sub
Call Main
The easiest way is to use built-in mshta.exe functionality:
sText = "Text Content"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(sText, "\", "\\"), "'", "\'") & "');close();""", 0, True
To put to clipboard a string containing double quote char ", use the below code:
sText = "Text Content and double quote "" char"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(Replace(sText, "\", "\\"), """", """"""), "'", "\'") & "'.replace('""""',String.fromCharCode(34)));close();""", 0, True
Take a look at this post. It describes a hacky approach to read from the clipboard, but I imagine it could be adapted to also write to the clipboard as well, such as changing the Ctrl+V to Ctrl+A then Ctrl+C.
I devised another way to use IE and yet avoid security warnings...
By the way.. this function is in JavaScript.. but u can easily convert it to VBScript..
function CopyText(sTxt) {
var oIe = WScript.CreateObject('InternetExplorer.Application');
oIe.silent = true;
oIe.Navigate('about:blank');
while(oIe.ReadyState!=4) WScript.Sleep(20);
while(oIe.document.readyState!='complete') WSript.Sleep(20);
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>";
var oTb = oIe.document.getElementById('txtArea');
oTb.value = sTxt;
oTb.select();
oTb = null;
oIe.ExecWB(12,0);
oIe.Quit();
oIe = null;
}
Here is Srikanth's method translated into vbs
function SetClipBoard(sTxt)
Set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.value = sTxt
oTb.select
set oTb = nothing
oIe.ExecWB 12,0
oIe.Quit
Set oIe = nothing
End function
function GetClipBoard()
set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.focus
oIe.ExecWB 13,0
GetClipBoard = oTb.value
oTb.select
set oTb = nothing
oIe.Quit
Set oIe = nothing
End function
In your Class ClipBoard, neither the Clear sub nor the Let Data sub work. I mean they have no effect on Windows Clipboard. Actually, and ironically so, the only sub that works is the one you have not included in your example, that is Get Data! (I have tested this code quite a few times.)
However, it's not your fault. I have tried to copy data to clipboard with ClipboardData.SetData and it's impossible. At least not by creating an "htmlfile" object. Maybe it works by creating an instance of "InternetExplorer.Application" as I have seen in a few cases, but I have not tried it. I hate creating application instances for such simple tasks!
Alkis
If it's just text can't you simply create a text file and read in the contents when you need it?
Another alternative and clearly a kludge, would be to use the SendKeys() method.
No security warnings and no carriage return at the end of line
' value to put in Clipboard
mavaleur = "YEAH"
' current Dir
path = WScript.ScriptFullName
GetPath = Left(path, InStrRev(path, "\"))
' Put the value in a file
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=GetPath & "fichier.valeur"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write mavaleur
objFile.Close
' Put the file in the Clipboard
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c clip < " & outFile, 0, TRUE
' Erase the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile outFile

Resources