Printing a web page from Windows Batch - windows

Is it possible to use a windows batch script to open a web page and print its contents to your default printer? Something simple as this:
#echo off
start /d IEXPLORE.EXE www.google.com
and now I want to send that page to the printer. But I am not sure of the syntax nor was I able to find anything specific or helpful on the web.
Does anyone know if it's possible to print a web page using a windows batch command?

Not from an iexplore switch, but vbscript will work:
Const PRINT = 6
Const DONTPROMPTUSER = 2
Const BUSY=4
Dim oIExplorer
Set oIExplorer = CreateObject("InternetExplorer.Application")
oIExplorer.Navigate "http://www.stackoverflow.com/"
oIExplorer.Visible = 1
Do while oIExplorer.ReadyState <> BUSY
wscript.sleep 1000
Loop
oIExplorer.ExecWB PRINT, DONTPROMPTUSER

Related

How to escape & ampersand in Custom protocol handler in Windows

I made a custom protocol handler following this link. The case is I need to open a link which can only be opened in IE and might contains several query parameters and should be opened in IE from our web app which is running on Chrome (this is really annoying). After many tries and fails, I managed to find the snippet to add entry to the windows registry hive and made .reg file and run:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\ie]
"URL Protocol"="\"\""
#="\"URL:IE Protocol\""
[HKEY_CURRENT_USER\Software\Classes\ie\DefaultIcon]
#="\"explorer.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\ie\shell]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open\command]
#="cmd /k set myvar=%1 & call set myvar=%%myvar:ie:=%% & call \"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe\" %%myvar%% & exit /B"
It worked but the problem is if a link contains more than 1 query params, all but the first are omitted, I am sure this because of character encoding in windows command line:
e.g. some_example_url?query1=value1&query2=value2&query3=value3 is becoming some_example_url?query1=value1
I find this solution but it did not work either. How can I properly escape & character, so that it can be opened on IE with all query parameters. (as before mentioned link is triggered by web app running on Chrome)
EDIT: The code which triggers:
fileClicked(url) {
// url should be escaped with ^
const escapedUrl = url.replace(/&/gi, '^&');
const ie = document.createElement('a');
// ie: scheme => custom protocol handler
// host computer (windows) should add custom protocol to windows registry
ie.href = `ie:${escapedUrl}`;
ie.click();
}
EDIT 2
#muzafako fixed the script, just last line should be replaced like below:
#="cmd /c set url=\"%1\" & call set url=%%url:ie:=%% & call start iexplore -nosessionmerging -noframemerging %%url%%"
You don't need to decode query parameters at all. I've tried to find solution for this issue and saw this answer. Its works for me. just change command line to:
#="cmd /c set url=\"%1\" & call set url=%%url:ie:=%% & call start iexplore -nosessionmerging -noframemerging %%url%%"

How to store the contents of the clipboard into a variable? [duplicate]

This question already has answers here:
Use clipboard from VBScript
(15 answers)
How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
(6 answers)
Closed 3 years ago.
Editor's note:
While this question is specifically about copying a file reference to the clipboard, its generic title led to answers about how to copy / get text.
As an Emacs user on Windows who often attaches files in mails, I have been looking for a utility to copy a file (not its contents) to the clipboard, just as windows explorer does on righclick/copy).
I just found this right here on SO which uses System.Windows.Forms.Clipboard` in a small program to do exactly that. But it is in C#, for which I don't have immediate access to a compiler. So I am wondering if this can be done and how.
I saw several references such as this that the clipboard is not accessible in VBScripting, but msdn shows documentation for VB so I am risking the question.
I have never written a VBScript before but I did try a few things before asking, starting with running a copy pasted a "Hello world" and then various combinations of CreateObject etc.
Update: I need to call Clipboard.SetFileDropList, so I do not think I can use ClipboardData as suggested by the answers, it does not have this method.
Update for visitors
The solution I ended up using was to compile the C# itself, I did not know I already had a compiler.
Another update for visitors
https://stackoverflow.com/a/29963268/18573 is what I am now using, quite happily.
You can do it with an html object to retrieve the contents of the clipboard:
' Get clipboard text
Set objHTML = CreateObject("htmlfile")
text = objHTML.ParentWindow.ClipboardData.GetData("text")
EDIT: I use this snippet to put text back on the clipboard, but it needs third party software; a standalone executable 'clip.exe' which can be found on Windows 2003 Server or just on the internet:
' Do something with the text
text = replace(text, "you ", "you and your dog ")
' Put it back to the clipboard
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine text
oIn.Close
(Yes, it is all a little bit hackerdyhack)
VBScript doesn't support the clipboard. Most hosts that host vbscript, such as Internet Explorer give access through the host. Therefore vbscript running in IE or an HTA can use IE's clipboard support. The scripting hosts do not give clipboard support. You can use a vbs file to start IE through COM automation, navigate to a local page (to bypass security warnings), then use IE's clipboard.
Here's a code snippit (Outp. is a text stream)
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate2 "C:\Users\David Candy\Desktop\Filter.html"
Do
wscript.sleep 100
Loop until ie.document.readystate = "complete"
txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
ie.quit
If IsNull(txt) = true then
outp.writeline "No text on clipboard"
else
outp.writeline txt
End If
You need this function (is a little modification of this):
'TO CLEAR
ClipBoard("")
'TO SET
ClipBoard("Hello World!")
'TO GET
Result = ClipBoard(Null)
Function ClipBoard(input)
'#description: A quick way to set and get your clipboard.
'#author: Jeremy England (SimplyCoded)
If IsNull(input) Then
ClipBoard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text")
If IsNull(ClipBoard) Then ClipBoard = ""
Else
CreateObject("WScript.Shell").Run _
"mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _
& Replace(Replace(Replace(input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _
0,True
End If
End Function
For the equivalent of a "paste" operation I would run a command-line utility like ClipOut or paste, redirect output to a file and read the file contents.
return = WshShell.Run("cmd /c clipout.exe > output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("output.txt", 1)
text = file.ReadAll
file.Close
You can get ClipOut here: http://jasonfaulkner.com/ClipOut.aspx
You can get paste here: https://www.c3scripts.com/tutorials/msdos/paste.html
For the equivalent of a "copy" operation I would use the clip command line utility that actually comes with Windows and similar code as above.
About the clip utility: https://blogs.msdn.microsoft.com/oldnewthing/20091110-00/?p=16093

How can I use Clipboard in vbscript? [duplicate]

This question already has answers here:
Use clipboard from VBScript
(15 answers)
How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
(6 answers)
Closed 3 years ago.
Editor's note:
While this question is specifically about copying a file reference to the clipboard, its generic title led to answers about how to copy / get text.
As an Emacs user on Windows who often attaches files in mails, I have been looking for a utility to copy a file (not its contents) to the clipboard, just as windows explorer does on righclick/copy).
I just found this right here on SO which uses System.Windows.Forms.Clipboard` in a small program to do exactly that. But it is in C#, for which I don't have immediate access to a compiler. So I am wondering if this can be done and how.
I saw several references such as this that the clipboard is not accessible in VBScripting, but msdn shows documentation for VB so I am risking the question.
I have never written a VBScript before but I did try a few things before asking, starting with running a copy pasted a "Hello world" and then various combinations of CreateObject etc.
Update: I need to call Clipboard.SetFileDropList, so I do not think I can use ClipboardData as suggested by the answers, it does not have this method.
Update for visitors
The solution I ended up using was to compile the C# itself, I did not know I already had a compiler.
Another update for visitors
https://stackoverflow.com/a/29963268/18573 is what I am now using, quite happily.
You can do it with an html object to retrieve the contents of the clipboard:
' Get clipboard text
Set objHTML = CreateObject("htmlfile")
text = objHTML.ParentWindow.ClipboardData.GetData("text")
EDIT: I use this snippet to put text back on the clipboard, but it needs third party software; a standalone executable 'clip.exe' which can be found on Windows 2003 Server or just on the internet:
' Do something with the text
text = replace(text, "you ", "you and your dog ")
' Put it back to the clipboard
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine text
oIn.Close
(Yes, it is all a little bit hackerdyhack)
VBScript doesn't support the clipboard. Most hosts that host vbscript, such as Internet Explorer give access through the host. Therefore vbscript running in IE or an HTA can use IE's clipboard support. The scripting hosts do not give clipboard support. You can use a vbs file to start IE through COM automation, navigate to a local page (to bypass security warnings), then use IE's clipboard.
Here's a code snippit (Outp. is a text stream)
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate2 "C:\Users\David Candy\Desktop\Filter.html"
Do
wscript.sleep 100
Loop until ie.document.readystate = "complete"
txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
ie.quit
If IsNull(txt) = true then
outp.writeline "No text on clipboard"
else
outp.writeline txt
End If
You need this function (is a little modification of this):
'TO CLEAR
ClipBoard("")
'TO SET
ClipBoard("Hello World!")
'TO GET
Result = ClipBoard(Null)
Function ClipBoard(input)
'#description: A quick way to set and get your clipboard.
'#author: Jeremy England (SimplyCoded)
If IsNull(input) Then
ClipBoard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text")
If IsNull(ClipBoard) Then ClipBoard = ""
Else
CreateObject("WScript.Shell").Run _
"mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _
& Replace(Replace(Replace(input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _
0,True
End If
End Function
For the equivalent of a "paste" operation I would run a command-line utility like ClipOut or paste, redirect output to a file and read the file contents.
return = WshShell.Run("cmd /c clipout.exe > output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("output.txt", 1)
text = file.ReadAll
file.Close
You can get ClipOut here: http://jasonfaulkner.com/ClipOut.aspx
You can get paste here: https://www.c3scripts.com/tutorials/msdos/paste.html
For the equivalent of a "copy" operation I would use the clip command line utility that actually comes with Windows and similar code as above.
About the clip utility: https://blogs.msdn.microsoft.com/oldnewthing/20091110-00/?p=16093

How to Clear Firefox Cache and Cookies from .VBS or Bat

Hello I want to clear Firefox cookies + cache from .vbs script or bat , i already have tried ccleaner /auto but the thing is it needs browser to be closed for clearing cache and cookies else it skips it , i would like to clear cookies and cache without closing the browser from either .vbs script or .bat script can you please give the code or recommend any other method ?
thanks
Enduros answer might help,however here is a short way of doing it if you have ccleaner installed you can call the ccleaner comaandline ccsetup.exe /S or use other various parameter options to do whatever specific task you might be interested here is a link to there comandline options ccleaner commandline parameters you would also use the folling sniplet
#include <File.au3>
Dim $sPath = #AppDataDir & '\Mozilla\Firefox\Profiles'
Dim $arr = _FileListToArray($sPath, '*.default', 2)
If IsArray($arr) Then
For $i = 1 To $arr[0]
FileDelete($sPath & "\" & $arr[$i] & "\cookies.sqlite")
Next
EndIf

How to play audio file on windows from command line?

In Windows, is there a simple way (i.e. something you could type on a single command line) to just play a couple of .mp3 files and then exit on its own?
wmplayer, for example, does not seem to exit when finished, forcing the harried user to hunt it down and click it closed every time. (wmplayer 11 also seems to strangely repeat some files if you pass it a list.)
(The older (1990's) versions of 'mplayer' used to support a '/close' command line option, but it doesn't seem to work in wmplayer 11.)
I'd prefer to use something that everyone will have on their machine (like wmplayer, quicktime...)
Old question, new answer - you could use PowerShell:
powershell -c (New-Object Media.SoundPlayer 'c:\PathTo\YourSound.wav').PlaySync();
I have used cmdmp3. Very lightweight at 28Kb.
Use VBScript:
Set objArgs = Wscript.Arguments
if (objArgs.Count = 0) then
Wscript.echo "I need a sound file as argument!"
WScript.Quit 123
end if
Wscript.echo "Playing: " & objArgs(0) & "..."
Set objPlayer = createobject("Wmplayer.OCX.7")
With objPlayer ' saves typing
.settings.autoStart = True
.settings.volume = 50 ' 0 - 100
.settings.balance = 0 ' -100 to 100
.settings.enableErrorDialogs = False
.enableContextMenu = False
.URL = objArgs(0)
WScript.Sleep(10000) ' time to load and start playing
'.Controls.Pause() ' stop
End With
MsgBox "if WMP is still playing, clicking OK will end it", _
vbInformation, "WMP Demo finished"
If the VBScript process ends, the Media Player ends too, you have to wait for it (I don't need it, my sounds are only some seconds long).
I used this for my special case today:
https://groups.google.com/forum/#!topic/microsoft.public.scripting.vbscript/gfOOvnN8t-U
There are pure command line players. Some are listed here.
Also, WinAmp used to have command line controller called CLAMP. I am not sure if it's still alive or available but Google for it - it was pretty good.
Also, VLC has some command line capabilities though I never checked them out.
This is what I did to do it:
rem Replace the following path with your music file
start C:\Users\Username\Desktop\your-music.mp3
rem Replace 10 with how many seconds you want the player to run
ping localhost -n 10 >nul
taskkill /im wmplayer.exe
Note this requires .mp3 to be associated with wmplayer.exe (Windows Media Player).
You can use fmedia to play audio files from Windows terminal:
fmedia file1.mp3 file2.mp3
This command will start the playback of file.mp3, then file2.mp3, and then quit after the files have finished playing.
If you wish to do it in background, add --background switch to your command:
fmedia file.ogg --background
This command will start a new process in background and detach from your console immediately.
fmedia is a portable application (works without installation) and consumes very small amount of system resources. Also, its startup time is instantaneous.
P.S. Use command fmedia.exe --install to add it to your %PATH% environment variable, otherwise you need to execute it with full path, e.g. D:\fmedia\fmedia.exe
You can probably write a small VBScript which will use the Windows Media Player ActiveX control to play an audio file. You should be able to terminate the process from that too, once playing finished.
I'm looking around a bit and maybe can come up with a working solution. Might take a while, though.
I am using this improve version of Mayra Delgado's answer:
Set objArgs = Wscript.Arguments
if (objArgs.Count = 0) then
Wscript.echo "I need a sound file as argument!"
WScript.Quit 123
end if
Wscript.echo "Playing: " & objArgs(0) & "..."
Set objPlayer = createobject("Wmplayer.OCX.7")
With objPlayer ' saves typing
.settings.autoStart = True
.settings.volume = 50 ' 0 - 100
.settings.balance = 0 ' -100 to 100
.settings.enableErrorDialogs = False
.enableContextMenu = False
.URL = objArgs(0)
' Wait until play finish
While .Playstate <> 1
Wscript.Sleep 100
Wend
End With
MsgBox "if WMP is still playing, clicking OK will end it", _
vbInformation, "WMP Demo finished"
I've found that the fastest way to play .mp3 files in Windows commandline is mpeg123
I know it's not available on people's machine per default, but from my point of view, Microsoft's own players are not consistently available over different versions either.
I'm using it on a project where the execution time is essential, and features like only playing certain frames makes is very useful. I find this (in my configuration) faster than the cmdmp3 and vbscript examples mentioned in this thread.
My syntax to only play certain frames of an .mp3 file :
mpg123.exe -k 2 -n 3 -q -1 -4 beep.mp3
Here are few scripts.
mediarunner.bat - it uses windows media player active x objects so you cannot used if there's no installed Windows Media Player (though it usually comes packed with the Windows).Accepts only one argument - the path to the file you want to play.
spplayer.bat - uses SP Voice objects but can play only .wav files.Again it accepts as only argument the path to the file you want to play.
soundplayer.bat - uses Internet Explorer objects and specific bgsound tag that can be used only in internet explorer.Can play .mp3,wav,.. files. It can accepts two arguments. The file you want to play and the sound volume (a number between -10000 to 0) :
call soundplayer.bat "C:\Windows\Media\Windows Navigation Start.wav" 0
If you need something cross-platform, mplayer works well on linux and windows and is compatible with npm's play-sound.

Resources