How To Ensure Vbscript Keeps Focus When Using Popup - vbscript

I have been trying without success to implement an unmodified Microsoft scriptas I would like to use it in a script I intend to work on - (see https://learn.microsoft.com/en-us/previous-versions/tn-archive/ee156593(v=technet.10)?redirectedfrom=MSDN Reference = Listing 3.32 Displaying Timed Progress Message Boxes). However, when I run that script exactly as presented on the page the first popup message appears OK then disappears as required but the two subsequent messages, although they are generated OK, they do not come to the forefront but remain in the background behind whatever else is on the page at that time.
Listing 3.32 Displaying Timed Progress Message:
your text```Const TIMEOUT = 5 your textSet objShell = WScript.CreateObject("WScript.Shell") your textobjShell.Popup "Disk Report Complete", TIMEOUT your textobjShell.Popup "Memory Report Complete", TIMEOUT your text``objShell.Popup "CPU Report Complete", TIMEOUT`
Can someone please run this same script off the page to see if they are getting the same result as I do. I have tried using vbSystemModal but it does not appear to be appropriate. The forum postings did not help me. If anyone can provide a solution as to why this script should not work properly I would be grateful.

You can bring a notice to the front reliably if you make it system modal:
MsgBox
MsgBox "Disk Report Complete",vbInformation+vbSystemModal,"Notice"
PopUp
Set oWSH = CreateObject("WScript.Shell")
oWSH.Popup "Disk Report Complete",5,"Notice",vbInformation+vbSystemModal
But I think a better option is to use the built-in notification system:
Toast-Example.vbs
Set oWSH = CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
MyFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
oWSH.CurrentDirectory = MyFolder
Sub Toast(Msg,Wait)
oWSH.Run "Powershell.exe -NoLogo -ExecutionPolicy Bypass -File .\Toast.ps1 """ & Msg & """",0,False
WScript.Sleep Wait * 1000
End Sub
Toast "Disk Report Complete",7
Toast "Memory Report Complete",7
Toast "CPU Report Complete",7
Toast.ps1 adapted from here
Param (
$Msg = ''
)
function Show-Notification {
[cmdletbinding()]
Param (
[string]
$ToastTitle,
[string]
[parameter(ValueFromPipeline)]
$ToastText
)
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
$Template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
$RawXml = [xml] $Template.GetXml()
($RawXml.toast.visual.binding.text|where {$_.id -eq "1"}).AppendChild($RawXml.CreateTextNode($ToastTitle)) > $null
($RawXml.toast.visual.binding.text|where {$_.id -eq "2"}).AppendChild($RawXml.CreateTextNode($ToastText)) > $null
$SerializedXml = New-Object Windows.Data.Xml.Dom.XmlDocument
$SerializedXml.LoadXml($RawXml.OuterXml)
$Toast = [Windows.UI.Notifications.ToastNotification]::new($SerializedXml)
$Toast.Tag = "My Notices"
$Toast.Group = "My Notices"
$Toast.ExpirationTime = [DateTimeOffset]::Now.AddMinutes(1)
$Notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("My Notices")
$Notifier.Show($Toast);
}
Show-Notification $Msg

Related

Use VBScript to show properties dialog/sheet - for multiple items

I'm trying to write a script in VBS to show the file properties dialog/sheet for multiple items. Those items will be all of the items in a parent folder (e.g. all items in W:\).
Essentially, I'm trying to get the properties dialog to show the number of files in a drive. Right-clicking on the drive and selecting Properties does not show the number of files. You would instead need to go into the first level of the drive, select all folders/files, and then right-click and select Properties.
I have customised some code (below) I've found on the internet to bring up the file properties dialog/sheet for either a specific folder, or a drive. I have no idea what I could further change to get the properties dialog for all files and folder of a specified drive. Perhaps getting all folders/files of the drive into an array and then working with that?
Please note I'm looking for the actual properties dialog, and not just a simple return of the total number of files (I know how to do this).
Any help would be appreciated! Thanks :)
Code:
dim objShell, objFSO, folParent, sParent, filTarget, sFileName, sOutput, fivVerbs, iVerb, vVerb, fvbVerb, testItemsParent, TestMappedDestination
set objFSO = CreateObject("Scripting.FileSystemObject")
set objShell = CreateObject("Shell.Application")
const mappedDestination = "c:\"
vVerb = "P&roperties"
sParent = objFSO.GetParentFolderName(mappedDestination)
sFileName = objFSO.GetFileName(mappedDestination)
If Len(mappedDestination) = 3 then
nsTarget = &H11
TestMappedDestination = "(" & UCase(Left(mappedDestination,2)) & ")"
Else
nsTarget = sParent
TestMappedDestination = UCase(sFileName)
End If
set folParent = objShell.Namespace(nsTarget)
For each filTarget in folParent.Items
If Len(mappedDestination) = 3 then
testItemsParent = UCase(Right(filTarget,4))
Else
testItemsParent = UCase(filTarget)
End if
If testItemsParent = TestMappedDestination then
Set fivVerbs = filTarget.Verbs
For iVerb = 0 to fivVerbs.Count - 1
If fivVerbs.Item(iVerb).Name = vVerb then
Set fvbVerb = fivVerbs.Item(iVerb)
fvbVerb.DoIt()
filTarget.InvokeVerbEx fvbVerb.Name, ""
Msgbox "Placeholder msgbox to keep properties dialog/sheet from disappearing on script completion"
Exit for
End if
Next
Exit for
End if
Next

Prevent overwrite pop-up when writing into excel using a powershell

I have a bunch of csv files from which I am writing data into a particular worksheet of an existing excel file. I have the below code and it works while looping through the CSV files and writing data into the existing worksheet
$CSVs ="rpt.test1",
"rpt.test2"
foreach ($csv in $CSVs)
{
$csv_name = $csv
echo "n - - - $sav_name - - -n"
foreach ($source in $Sources)
{
$src = $source
$inputCSV = "C:\Users\xxxx\Desktop\$src.$csv_name.csv"
$Path = "C:\Users\xxxx\Desktop\$csv_name.xlsx"
### Create a new Excel Workbook with one empty sheet
#$excel = New-Object -ComObject excel.application
#$workbook = $excel.Workbooks.Add(1)
#$worksheet = $workbook.worksheets.Item(1)
# Open the Excel document and pull in the 'Play' worksheet
$excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($Path)
$page = 'data'
$worksheet = $Workbook.worksheets | where-object {$_.Name -eq $page}
# Delete the current contents of the page
$worksheet.Cells.Clear() | Out-Null
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
$Workbook.SaveAs($Path,51)
$excel.Quit()
}
Since it is an existing excel workbook, it throws a pop-up every time a file is being over-written. Have more than 15 CSV's and clicking Yes everytime is annoying
I have tried
$excel.DisplayAlerts = FALSE
and I have tried
$excel.CheckCompatibility = $False
and pretty much anything available on the internet. I am still learning powershell and at my wits end trying to stop this. Any help would be very much appreciated
Use display alerts statement before the SaveAs call:
$excel.DisplayAlerts = $false;
$excel.ActiveWorkbook.SaveAs($xlsFile);
$excel.DisplayAlerts = $false worked for me.

QTP AOM code to enable image capture on script failure is not working

QTP AOM code to enable image capture on script failure is not working
I am using the below code to enable the QTP Screen Capture option but it's not storing any screenshots:
Code:
Dim App
Dim qtTest
'Create the QTP Application object
Set App = CreateObject("QuickTest.Application")
'If QTP is notopen then open it
If App.launched <> True then
App.Launch
End If
'Make the QuickTest application visible
App.Visible = True
'Set QuickTest run options
'Instruct QuickTest to perform next step when error occurs
App.Options.Run.ImageCaptureForTestResults = "OnError"
App.Options.Run.RunMode = "Fast"
App.Options.Run.ViewResults = True
'Open the test in read-only mode
App.Open "D:\GUITest4", True
'set run settings for the test
Set qtTest = App.Test
'Instruct QuickTest to perform next step when error occurs
qtTest.Settings.Run.OnError = "NextStep"
'Run the test
qtTest.Run
'Check the results of the test run
MsgBox qtTest.LastRunResults.Status
' Close the test
qtTest.Close
'Close QTP
'App.quit
'Release Object
Set qtTest = Nothing
Set App = Nothing
Can anyone help?
Try this to capture screenshots:
set obj = Desktop
obj.capturebitmap strFileName & ".png"
To have the screenshot embedded in results itself, give the path of results in strFileName parameter as:
strFileName = Environment.Value("ResultDir") & "\" & Mid(Environment.Value("ActionName"), 1, 15) & filename.png
Using QTP AOM we can capture the screenshot which will be stored in the results folder , can be controlled via below code.
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Options.Run.ImageCaptureForTestResults = "OnError"
qtApp.Open "C:\Tests\Test1", True
Set qtTest = qtApp.Test
Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions")
Create the Run Results Options object
qtResultsOpt.ResultsLocation = "C:\Tests\Test1\Res1"
Set the results location
qtTest.Run qtResultsOpt
Run the test
qtTest.Close
Hope it helps, let me know the results

How to disable SmartScreen for a specific .cmd file?

I recent made a group of .cmd files.
Called, 'Node.1.cmd' and 'Node.2.cmd', the files' purpose was supposed to open each other (in a chain-like process).
However, whenever I open one of the 2, it gives me a seriously annoying message:
Windows Protected your PC.
Windows SmartScreen prevented an unrecognized app from starting. Running this app may put your PC at risk.
I agree that this is a bit risky, but it was made for fun, not for destruction. It was just my way of showing people not to mess with my stuff. Not even did I set any LNK at my desktop to the file.
Now, to get to the point, can I exclude this file from SmartScreen while keeping it on?
Because of this, I have problems opening it with a .vbs file
To be more specific, it opens but then automatically closes with a message:
The system cannot find the path specified.
Does windows SmartScreen encrypt the file or something like that?
I scripted the following:
Titre = "What would you like to do ? RookieTEC9©"
message = "What would you like to do ?"&vbcr&vbcr&_
"1 - Launch Project Node "&vbcr&_
"2 - Launch Golden Chrome"&vbcr&_
"3 - Launch An Application"&vbcr&_
"4 - Start Windows Update"&vbcr&_
"5 - Slide2Kill"
Default ="1"
Question = InputBox(message,Titre,Default)
Select Case Question
Case 1 Run(1)
Case 2 Run(2)
Case 3 Run(3)
Case 4 Run(4)
Case 5 Run(5)
end Select
Sub Run(var)
Set WS = CreateObject("WScript.shell")
Select Case var
Case 1 WS.run("explorer.exe /e,C:\Users\Jeremi\OneDrive\Happy_files\Unsorted_Files\Project_Node.zip\Node.1.cmd")
Case 2 ProcessNotNeeded()
Case 3 LaunchApplication()
Case 4 WindowsUpdate()
Case 5 WS.run("SlideToShutDown.exe")
End select
End Sub
Sub Kill(Process)
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
Sub ProcessNotNeeded()
Titre = "Killing Process Not Needed RookieTEC9© "
message = "Type the Name of the process to be killed by this script"&vbcr&_
"Example To Kill The Internet Explorer Process You should type"&vbcr&_
"iexplore.exe"
Default ="iexplore.exe"
Question = InputBox(message,Titre,Default)
Kill(Question)
End Sub
Function CmdPrompt(sCmd)
Dim sCmdLine,oWS,nRes
set oWS = CreateObject("Wscript.Shell")
sCmdLine = "cmd /c Start " & sCmd & ""
nRes = oWS.Run(sCmdLine,0,False)
CmdPrompt = nRes
End Function
Sub LaunchApplication()
Titre = "Launching an Application"
message = "Type the Name of the process to be Lanuched by this script"&vbcr&_
"Example To Launch The Word Application You should type"&vbcr&_
"Winword.exe"
Default ="Winword.exe"
Question = InputBox(message,Titre,Default)
CmdPrompt(Question)
End Sub
Sub WindowsUpdate()
Title = "Checking for Windows updates"
Msg = "Looking for a list of updates, So be Patient Thank you !"
Wait = "70" 'waiting 70 secondes to close the popup
Set Ws = CreateObject("Wscript.Shell")
ws.Popup Msg,wait,Title,64
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
If searchResult.Updates.Count <> 0 Then 'If updates were found
'so with this loop shows how you can list the title of each update that was found.
For i = 0 To searchResult.Updates.Count - 1
Set update = searchResult.Updates.Item(i)
ws.Popup update.Title,wait,Title,64
Next
End If
Ws.Run "wuauclt.exe /reportnow /detectnow",1,False
End Sub
Sorry for the long code!
To be 100% honest, I didn't create this from scratch, I just edited it.
I am new to VBS
However, if you have any questions on HTML or CSS, I may be able to answer it.
Please keep in mind that I am a 5th grader and only started coding this school year.
THX for your time and answer.
P.S.
Also, the file was in a zip. Does that effect it?
You can unblock these CMD files, it is explained here
Once unblocked you should be able to run it from the console and from your script.
I myself scripted a very long time in vbscript but now it is obsolete. Since you have
just started to learn, I advise you to learn another scripting language like Ruby which is fun to learn or if you want to go the 'only windows' way Powershell (shiver..)

Verify what website I am currently on

Does anyone know of a quick and easy way to verify what website I'm currently on?
I have made some script that logs me into a website, but if the user is already logged on, it will create an error.
If anyone knows a good way to tell if they are already logged in, please let me know!
The script is as follows:
Username = InputBox("Please input username")
Password = InputBox("Please input password")
Set objShell = WScript.CreateObject("WScript.Shell")
Dim IE
Set IE = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
IE.Visible = 1
IE.navigate "http://wsmmart.itg.ti.com/"
Do
WScript.Sleep 250
Loop While IE.ReadyState < 4 And IE.Busy
IE.Document.All.Item("fld2").Value = Username
IE.Document.All.Item("fld5").Value = Password
'IE.Document.All.Item("Submit").Click
The following code will loop through all open IE windows and look to see if any one of them has the term "wsmmart.itg.ti." in the url. If it finds a match it will control that window and proceed to insert your username, pw, etc. If it doesn't find a match then you could run your code to open a new window
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
my_url = objShell.Windows(x).Document.Location
If my_url Like "*" & "wsmmart.itg.ti." & "*" Then 'find an existing wsmmart web page
Set ie = objShell.Windows(x)
Exit For
Else
if x=(IE_count - 1) then
' do your stuff to open a new window
end if
End If
Next
on error goto 0
now try to insert your username, pw, etc. , put it in an if statement. if you get an error back, then you're already logged in

Resources