Bat file based pop up window autoplay when USB is connected - batch-file

What is the best way to do the following:
When I connect my device (let it be specific device - say Google Glass) to the USB port, I'd like that some agent will immediately pop-up (like windows autoplay), show me the list of files I currently have in the device, let me pick which one to upload to an ftp server, and at the end some "Upload" button in order to upload the chosen files to the ftp I would pre-define it.
I also would like that after the user picks the files, it will rename the filesnames according to a pre-defined rule and only after that will upload it to the server.
Is there a way to do this? is there a tool that already does this or something similar?
I alreay wrote a .bat file with a script that can do the renaming and the uploading, so if there's some way to run the script when I press the "Upload" button it would be great.

If you start the script with cscript it will write to a console rather than message boxes.
cscript <path to script>
E.G.
cscript "c:\somefolder\DeviceArrival.vbs"
Removable drives are drivetype=2. Create C:\Test first. Note I've changed the event type from all devices to just add/remove a drive.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(objitem.driveletter)
Set DestFldr=objShell.NameSpace("c:\test\")
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Wscript.Echo "Finished Copying"
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop
Here's sample script that waits for devices to arrive/leave.
Note it runs twice so you may want to improve it because there are two notifications for each arrival. Also there needs to be checks done eg if you plug in one USB stick while another is plugged in both will be copied.

Related

Is there a way to run a .cmd file when a specific program is closed?

I want the program GOPHER.exe to close when I close Netflix. I already have it set so that when I open Netflix, GOPHER also opens. Right now the command in the .cmd file to close GOPHER is "TASKKILL /IM gopher.exe". I want it to run when I close Netflix.
This monitors for programs exiting using WMI (MS's implementation of WBEM). Here it checks for Notepad exiting and restarts it.
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
Msgbox "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop

How to open an HTML file from a batch file in default browser with a specific destination anchor?

I am trying to open an HTML file with a specific destination anchor from a batch file like so:
start iexplore %~dps0nl752.htm#01
exit
nl753.htm is on the local drive.
How can I get Windows to open the HTML file with the destination anchor in the default browser instead of Internet Explorer?
If you want to start the default browser then you should obviously not hardcode iexplore! The start command will figure out the system default on its own based on the file extension or URL protocol.
On my Windows 8.1 machine anchors work fine:
start "" "http://example.com#whatever"
it does seem to work without quotes as well but I personally prefer them just in case there is a space or a & there.
In my experience Internet Explorer will sometimes do some kind of internal redirection when dealing with local .htm[l] files and/or file:// URLs and this seems to strip away the anchor. There is not much you can do about that.
Just to be clear, appending a anchor to a plain file system path will not work because it technically changes the extension. A file:// URL will work because Windows only looks at the protocol when dealing with URLs.
On my system start "" "file:///C:/Program%20Files/Common%20Files/microsoft%20shared/Stationery/Soft%20Blue.htm#whatever" does work as far as accepting the command and starting the browser. This does not mean that the browser will respect the anchor but that is a implementation detail in the browser that you have no control over and results might vary depending on which browser is the default.
If this is not good enough then you can try using IE Automation to start and control Internet Explorer. This means you have to give up using the users default browser and I would not recommend it for this reason...
Relying on the file:// protocol and a .html extension to execute a browser and not a HTML editor is somewhat risky as pointed out in another answer but I'm not sure if I would dare to query the registry in a batch-file either.
The absolute best solution is to call ShellExecuteEx with a forced progid but that is only possible in a real application.
The second best solution is to write a Windows Scripting Host script instead of a batch file since it is much safer to read and parse the registry there...
In the case of opening files, using file:// is the same as calling the file directly.
That is,
start "" "file://%cd:\=/%/myfile.html"
is the same as
start "" "myfile.html"
Which is all well and good if your default program for opening HTML files is a browser, but it may not be.
To use the browser, the only thing I can think of is getting it from the registry:
#echo off
setlocal EnableDelayedExpansion
for /F "tokens=3" %%i in ('reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice /v ProgID') do for /F "tokens=2*" %%j in ('reg query HKEY_LOCAL_MACHINE\Software\Classes\%%i\shell\open\command /ve') do set cmd=%%k
start "" !cmd:%%1=file://%cd:\=/%/%1!
To explain, this retrieves the association with the "http" URL schema then looks up the execution command for that entry and stores it in cmd. We use %%k instead of j here because it will likely contain spaces, so 2 (%%j) selects the second entry in the return from reg then collected the rest into %%k.
Then it uses start to call the cmd with the target file (%1 here) is spliced into the %1 in the cmd. We assume the passed command is relative and make it absolute by prefixing it with the %cd% with the \ replaced with / as URLs need, then prefixed with the file schema for the browser.
I don't know how robust this is offhand, for instance the registry addresses my be different per system (I did this on Win10).
To open file from cmd Type:
start "index.html"
ShVerb
Lists or runs an explorer verb (right click menu) on a file or folder
ShVerb <filename> [verb]
Used without a verb it lists the verbs available for the file or folder
The program lists most verbs but only ones above the first separator
of the menu work when used this way
The Properties verb can be used. However the program has to keep running
to hold the properties dialog open. It keeps running by displaying
a message box.
The VBS script is
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo(Cmd.doit)
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If
It gives output like this when listing available verbs
C:\Windows\system32>cscript //nologo "C:\Users\User\Desktop\ShVerb.vbs" "C:\Users\User\Desktop\Filter.html"
Open
Open in Same Window
Print
Restore previous versions
Cut
Copy
Create shortcut
Delete
Rename
Properties
To use to open an html page.
cscript "C:\Users\User\Desktop\Bat&Vbs\ShVerb.vbs" "C:\Users\User\Desktop\Filter.html" Open
To start any file in the system defaults you need to use the 'start' command on Windows 10 (Not sure about lower versions but I'm guessing it will be about the same) & 'open' for MacOS Terminals.
On Windows,
To open any file use:
*start 'filename.format'
This should open up the files in default applications, like HTML files in browsers, images in albums, etc.

Close a program at a set time after opening

I'm looking to make a batch file that will close a program at a set time after opening it. So, for example, if I open my email program, the batch file will be triggered, and after two minutes, my email will automatically close. If possible, I would also like the command window to open hidden. I tried working with the Event Logger and the Task Scheduler, but I got nowhere fast.
Any suggestions?
Thanks!
Run Command hidden
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /k dir c:\windows\*.*", 0, false
This detects when an app exits. Here when notepad exits it restarts it. You can alter it to process starts, stops, or both. Win32_ProcessStopTrace, Win32_ProcessStartTrace, and Win32_ProcessStartStopTrace.
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
Msgbox "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
This goes through the list of running processes and if Calculator terminates it.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
To have a script wait. From Help at https://www.microsoft.com/en-au/download/details.aspx?id=2764
Suspends script execution for a specified length of time, then continues execution.
object.Sleep(intTime)
object
WScript object.
intTime
Integer value indicating the interval (in milliseconds) you want the script process to be inactive.
So wscript.sleep 120000 is two minutes
I'll leave you to tie it together.

VB script within HTA Getting script to check service and loop until its started

This is going in an HTA and have checked the VB Script for HTA compatibility. While its clear I don't have a scooby about most of the VB Scripting language I try my best.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\Cimv2")
Set colItems = objWMIService.ExecQuery( _
"Select * From Win32_Service where Name= 'spooler'")
For Each objItem In colItems
If objItem.State = "Running" Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute """C:\Program Files\Program\program.exe"""
ElseIf objItem.State = "Stopped" Then
Empty code area
End If
Next
In the empty code area , I am struggling to get something working. I tried:
Do
Loop Until objItem.State = "Running"
This caused the HTA to hang as a "warning Script is not responding error".
Currently trying to find something along those lines but just wondered if anybody had any better suggestions.
Cheers
D
I have done some investigations. colItems seems to be of type SWbemObjectSet. This is a COM object which does not behave like most VB, VBA, VBScript collections. This should work:
Dim i
For i = 0 To colItems.Count - 1
If colItems.ItemIndex(i).State = "Running" Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute """C:\Program Files\Program\program.exe"""
Exit For
End If
Next i
I also added an Exit For because you want to start program.exe only once.

Batch or VB script to initiate Win7 RunAs login box?

I'm looking for a batch command or VBscript to execute what would a Shift+Right-click > "Run as different user" It pops up with a login box that just says "Windows Security" in the title
http://i.imgur.com/EDeCCND.jpg
I've searched far and wide and the closest I've gotten was the "runas" from the command line, and I've found a VBscript that can do "Run as administrator." But I just want a script that will initiate a login box like in the picture above, which is the same as the "Run as different user"
Thanks
Edit - Some background of my issue:
I have a batch file that I use to install software to remote computer via psexec, as well as running some scripts and stuff. Now in order to run my batch file successfully, the user will need to run it under a domain admin account. And I'm basically trying to force that to happen.
At first I tried forcing the UAC to come up via this beautiful script...and that works great! Unfortunately I found out that will not work if a local administrator is logged on and launches the file (it will see that it already has admin rights on the local machine, but it won't have rights on the remote machine when it goes to run psexec).
I can't really do a runas via batch because I don't know what domain admin is going to be running the batch. I also would rather not have the user enter their credentials in a command line window...And I could just tell them to do the shift+right-click on the bat file, but I'd like to avoid that if possible, since users can be forgetful :)
So the solution to my problem, I believe, is a script that will do exactly what a Shift+right-click > "Run as different user" will do.
Any help is greatly appreciated
Shverb - Lists or runs an explorer verb (right click menu)
Drag and drop or use in a command line.
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo Cmd.doit
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If
also
wmic /node"#%userprofile%\desktop\ComputerName.txt" /user:username /password:password /failfast:on process call create c:\somefile.bat
It has help built in. The first three lines are the help file.
ShVerb
Lists or runs an explorer verb (right click menu) on a file or folder
ShVerb <filename> [verb]
Used without a verb it lists the verbs available for the file or folder
The program lists most verbs but only ones above the first separator
of the menu work when used this way
The Properties verb can be used. However the program has to keep running
to hold the properties dialog open. It keeps running by displaying
a message box.
You'll have to run it on the remote system.
But the two command line tools allow passwords to be entered. And as I've shown you can put the user name in automatically.

Resources