0% found this document useful (0 votes)
101 views28 pages

Real'S Howto PDF Version

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views28 pages

Real'S Howto PDF Version

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Real's HowTo PDF version

Real's HowTo PDF version

Table of Contents
Real's HowTo PDF version (november 2015)..................................................................................................1

Misc Prog HowTo...............................................................................................................................................3


gp.............................................................................................................................................................3
Generate text in MS Word.......................................................................................................................3
Display HLP files with Vista...................................................................................................................4
Create a file association with a Java program..........................................................................................5
Open Windows explorer with a file selected...........................................................................................6
Start a screen saver...................................................................................................................................7
Schedule a task from the command line..................................................................................................7
Create an Internet shortcut.......................................................................................................................7
Kill a process from the command line.....................................................................................................8
Disable Internet Explorer Developer Tools.............................................................................................8
Detect if a process is running using WMIC.............................................................................................9
Detect if running in VM.........................................................................................................................10
Integrate with Skype, Microsoft Communicator or Outlook feed using special URI...........................10
Manipulate the registry from a batch file...............................................................................................11
Filename parsing in batch file and more idioms....................................................................................13
Arguments handling in a batch file........................................................................................................14
Create a file with the name as the current date......................................................................................15
Set an environment variable from a text file content.............................................................................16
ECHO "<" or ">" in a batch file............................................................................................................17
Test if a file exists or not........................................................................................................................17
Touch a file............................................................................................................................................18
Quickly delete files................................................................................................................................18
Quickly get how many files in a directory.............................................................................................19
Turn CAPSLOCK on/off from a batch file............................................................................................19
Increment a counter in a batch file.........................................................................................................20
Open Windows Explorer on specific special folder..............................................................................20
Get desktop path from a batch file.........................................................................................................21
Display a popup from a batch file..........................................................................................................21
Download a file from a batch file..........................................................................................................22
Open a PDF at a specific page...............................................................................................................22
Convert a PS file to PDF or TIF using Ghostscript...............................................................................22
Convert a PDF to Postscript using Ghostscript.....................................................................................23
Convert PDF to TIF (TIFF) using Ghostscript......................................................................................24
Merge PDF's (with Ghostscript)............................................................................................................24
Hide information in your email address.................................................................................................25
Google "little-known" features..............................................................................................................25

i
Real's HowTo PDF version (november 2015).
This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ). For
up-to-date content, please refer to the Web site. There are 4 files : Real's Java , Real's Javascript, Real's
Powerbuilder and Real's VBS and Misc Prog HowTo. Please don't make PDF versions available on the
internet (it's ok in intranet). From the PDF, you can't run the examples and the links to other How-to's are not
working.

If you feel that effort has been useful to you, perhaps you will consider giving something back? You can make
a donation through PayPal at https://www.paypal.com , make you donation to [email protected]
Contributions via PayPal are accepted in any amount using a credit card or checking account.

(Donations of any size gladly accepted)

This site is covered by the Creative Commons by-nc-sa license :


You can share, adapt and reuse but not for commercial reason. See the FAQ

Real's Howto copyright notice ( [email protected] )

Redistribution and use in source and binary forms,


with or without modification, are permitted provided
that the following conditions is met:

* the source code is used in a development project

Redistributions of source code or site content


(even partially) in any publications (electronic or paper)
is forbidden without permission.

DISCLAIMER

THIS CONTENT IS PROVIDED BY Real Gagnon "AS IS" AND ANY


EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Real's HowTo PDF version (november 2015). 1


Real's HowTo PDF version

Real's HowTo PDF version (november 2015). 2


Misc Prog HowTo
gp

Generate text in MS Word


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0001.html

Word2003
Open a new document in word and type without a space

=rand(10,1)

and press [ENTER] and Word will generate 10 paragraphs with one sentence in each one.

The output with the french version of Word :

Servez à ce monsieur une bière et des kiwis


Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis
Servez à ce monsieur une bière et des kiwis

The output for the english version :

The quick brown fox jumps over the lazy dog


The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog

The first parameter is for how many paragraphs you want and the second parameter controls the length of a
paragraph.

Misc Prog HowTo 3


Real's HowTo PDF version

With Word 2007, the rand function picks random text from the Word help instead. The previous behaviour is
still available with the rand.old().

Starting with Word 2007, a new function is available to generate Lorem Ipsum text filler. The function is

=lorem(paragraphs,sentences)

for example

=lorem(2,5)

generates

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa.
Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet
commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est.

Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada


fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem.

Another trick is to generate a separator line.

At the beginning of a line, type 3 special characters and a seperator will be inserted. Depending on the
characters typed, the style of the seperator will change.

--- Thin line


*** Broken line
### Thick line with two thin lines
=== Double line
~~~ Wavy line

and the result is

Display HLP files with Vista


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0010.html

Generate text in MS Word 4


Real's HowTo PDF version

Starting with the Windows Vista operating system release, the Windows Help program will not ship as a
component of the Windows operating system. Also, third-party programs that include .hlp files are prohibited
from redistributing the Windows Help program together with their products.

http://support.microsoft.com/?kbid=917607

Users who want to view 32-bit .hlp files must download the program from the Microsoft Download Center,
and then install it on their computers.

To download WinHlp32.exe, visit the following Microsoft Web site:


http://go.microsoft.com/fwlink/?LinkID=82148

Create a file association with a Java program


Current version of this HowTo :
http://www.rgagnon.com/gp/../javadetails/java-0592.html

In this example, a file with the extension .xox will be defined and associated with a java program (display the
first 10 lines of selected .xox file).

First the java program to be associated with the .xox file type.

import java.io.*;

public class Head {


static final int MAX_LINES = 10;
public static void main(String args[]) throws Exception{
String line = null;
int i = 0 ;
FileInputStream fin = new FileInputStream(args[0]);
BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin));
while ( (line = myInput.readLine()) != null) {
System.out.println(line);
i++;
if (i == MAX_LINES) break;
}
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("*** Press any key...");
input.readLine();
}
}

Display HLP files with Vista 5


Real's HowTo PDF version

With Windows, two commands are used to define a file association, assoc and ftype. You need to execute
these commands from an account with Administrator privilege.

To know more about these commands, type assoc /? or ftype /? .

First we define the .xox file type.

The assoc command sets up an association between a file name extension and a file type.

>assoc .xox=Xoxfile
.xox=Xoxfile

Then we specify which program is used to handle the Xoxfile type of file.

The ftype command sets up an association between a file type name, and a string to be used to execute it.

In this example, we specify the Java JVM to be used, the classpath to load the Head.class plus the parameter
(the selected .xox file).

>ftype Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java -cp c:\dev\work Head %1


Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java -cp c:\dev\work Head %1

Now, if you double-click on a file with .xox extension, a Dos shell is opened, the Head class is launched with
the clicked filename as a parameter and the first 10 line are displayed.

To make the file association works from a command line, you define the environment variable PATHEXT to
include the .xox extension.

>set pathext=.xox;%pathext%
PATHEXT=.XOX;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

then you will be able, from a Dos shell, to type only the name of .xox file and the associated program will be
launched with that file as a parameter.

See also this HowTo.

Open Windows explorer with a file selected


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0011.html

Simple explorer with the file selected

explorer /select,c:\windows\win.ini

Create a file association with a Java program 6


Real's HowTo PDF version

Simple explorer with the file selected plus the treeview expanded.

explorer /e, /select, c:\windows\win.ini

See also this HowTo.

Start a screen saver


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0012.html

To start a given screen saver.

scrnsave.scr /s

or

start scrnsave.scr /s

Note : SCR files are habitually located in the \Windows\system32 directory.

Schedule a task from the command line


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0013.html

On Windows Server 2000/2003, you use the SCHTASKS utility.

Microsoft Technet

Example:

> schtasks /create /tn "MyTest4" /s mymachine.local


/tr "cmd.exe /c d:\test.cmd" /sc once /st 16:30:00

Create an Internet shortcut


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0018.html

An Internet shortcut is simple text file with the .URL extension.

Open Windows explorer with a file selected 7


Real's HowTo PDF version

A link to Google looks like this :

[InternetShortcut]
URL=http://www.google.com
IconFile=http://www.google.com/favicon.ico
IconIndex=0

You can create it with a regular text editor, just make sure that you give a filename with a .URL extension.

From a batch file, you can do something like this :

echo [InternetShortcut] > "%userprofile%\Desktop\Google.URL"


echo URL=http://www.google.com >> "%userprofile%\Desktop\Google.URL"
echo IconFile=http://www.google.com/favicon.ico >> "%userprofile%\Desktop\Google.URL"
echo IconIndex=0 >> "%userprofile%\Desktop\Google.URL"

See this HowTo to see how to do it in Java.

Shortcut to a program locally installed can be created with a VBScript, see this HowTo.

Kill a process from the command line


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/windows-kill-process-command-line.html

FIrst, get the process id with TASKLIST

tasklist /fi "imagename eq java.exe"

output :

Image Name PID Session Name Session# Mem Usage Status


=================== ====== ============= ======== ============
Java.exe 1060 RDP-Tcp#8 0 81 408 Ko

the use TASKKILL <pid>

taskkill /pid 1060

Disable Internet Explorer Developer Tools


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/disable-ie-developer-tools.html

Create an Internet shortcut 8


Real's HowTo PDF version

Add a DWORD value with the name "Disabled" and give it the value "1"

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IEDevTools
"Disabled" = 1

Detect if a process is running using WMIC


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/windows-detect-if-a-process-is-running.html

WMIC is a powerful Windows utility. You can use to know if a particular process is running or not.

This example detects if a Tomcat instance (can be anything, ex: Apache or Excel) is running from a batch file.

@echo off
wmic process list brief | find /i "tomcat.exe"
set result=%ERRORLEVEL%
if "%result%"=="1" echo "not running"
if "%result%"=="0" echo "running"

/i is to make the find operation case-insensitive.

For Java code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class WindowsUtils {


private WindowsUtils() {}
public static boolean isProcessRunning(String processName) throws IOException {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;

List<String> command = new ArrayList<String>();


command.add("WMIC");
command.add("process");
command.add("list");
command.add("brief");

try {
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
is = process.getInputStream();
isr = new InputStreamReader(is);

Disable Internet Explorer Developer Tools 9


Real's HowTo PDF version

br = new BufferedReader(isr);
String line;
processName = processName.toUpperCase();
while ((line = br.readLine()) != null) {
if (line.toUpperCase().indexOf(processName) > -1) return true;
}
return false;
}
finally {
if (br != null) br.close();
if (isr != null) isr.close();
if (is != null) is.close();
}
}

public static void main(String[] args) throws IOException {


System.out.println(WindowsUtils2.isProcessRunning("excel.exe"));
}
}

See also this HowTo.

Detect if running in VM
Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/windows-detect-if-running-in-a-VM.html

Using WMIC.

@echo off
wmic bios list full | find /i "vmware"
set result=%ERRORLEVEL%
if "%result%"=="1" echo "not running in a VM"
if "%result%"=="0" echo "running in a VM"

/i is to make the find operation case-insensitive.

Integrate with Skype, Microsoft Communicator or Outlook feed


using special URI
Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-integrate-your-app-with-skype-communicator-or-outlook-feed-using-special-URI

Detect if a process is running using WMIC 10


Real's HowTo PDF version

Skype

When you install the Skype client, a new protocol is created : skype:

The syntax is

skype:[?[add|call|chat|sendfile|userinfo]]

in HTML, it looks like this

<a href="skype:1235551234?call">Skype me<a>

Microsoft Communicator

The protocol to use is im:

ex.

<a href="im:sip:[email protected]">Chat with Chuck</a>

Outlook feed

To add a RSS feed to Outlook is not the most easy task. The protocol outlookfeed: can make the process
a little bit easier.

<a href="outlookfeed://www.rgagnon.com/feed.xml">Real's HowTo Feed<a>

Try it (if you have Outlook installed) : Real's HowTo Feed

Manipulate the registry from a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0005.html

CAUTION! Working with the registry can be dangerous!

REGEDIT is usually known as a GUI tool to search or edit the Windows registry but we can use it in batch
file too.

The syntax to update the registry is

REGEDIT.EXE /S importfile.REG

/S is to hide confirmation box when importing files.

Integrate with Skype, Microsoft Communicator or Outlook feedusing special URI 11


Real's HowTo PDF version

You can use notepad or wordpad to write registry files, you save them with a .reg extension.

The first line in the registry file for XP or 2000 has to be :

Windows Registry Editor Version 5.00

For Win98, ME, or NT 4.0 it's :

REGEDIT4

then the header is followed by a blank line.

To create a key

[HKEY_CURRENT_USER\Software\RealHowto]

To create a value

[HKEY_CURRENT_USER\Software\RealHowto]
"MyValue"="howto"

To remove a key

[-HKEY_CURRENT_USER\Software\RealHowto]

To remove a value

[HKEY_CURRENT_USER\Software\RealHowto]
"ValueToBeRemoved"=-

By default, a value is a string. To specify a dword simply use the prefix dword :

[HKEY_CURRENT_USER\Software\RealHowto]
"MyValue"=dword:000001

If a semicolon is in front of any line then it will be ignored, it's the way to comment a REG file.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\RealHowto]
; add a value
"MyValue2"=dword:00000001
; delete a value
"MyValue1"=-

Manipulate the registry from a batch file 12


Real's HowTo PDF version

Filename parsing in batch file and more idioms


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0008.html

In the following examples, we iterate a list of files and use the idiom ~[idiom] to extract certain part of a
given filename.

Extract the filename without the extension : ~n

for %i in (*.*) do echo %~ni

Extract the file extension without the filename : ~x

for %i in (*.*) do echo %~xi

Extract the file attribute : ~a

for %i in (*.*) do echo %~ai

Extract the file time : ~t

for %i in (*.*) do echo %~ti

Extract the drive only : ~d

for %i in (*.*) do echo %~di

Extract the path only : ~p

for %i in (*.*) do echo %~pi

Extract the complete name : ~s

for %i in (*.*) do echo %~si

Extract the file length (in bytes) : ~z

for %i in (*.*) do echo %~zi

%~$PATH:i searches the directories listed in the PATH environment variable and expands %I to the fully
qualified name of the first one found. If the environment variable name is not defined or the file is not found
by the search, then this modifier expands to the empty string.

for %i in (java.exe) do @echo. %~$PATH:i

Filename parsing in batch file and more idioms 13


Real's HowTo PDF version

To remove quotes

>for %i in ("real'howto") do @echo. %i


"real'howto"
>for %i in ("real'howto") do @echo. %~i
real'howto

The path (with drive) where the script is : ~dp0


set BAT_HOME=%~dp0
echo %BAT_HOME%
cd %BAT_HOME%

The path (without drive) where the script is : ~p0

set BAT_HOME=%~p0
echo %BAT_HOME%
cd %BAT_HOME%

The drive where the script is : ~d0

set BAT_DRIVE=%~d0
echo %BAT_DRIVE%

The complete script name : ~s0

set BAT_PATH=%~s0
echo %BAT_PATH%

The script name only (as called with or without the extension): %0

set BAT_NAME=%0
echo %BAT_NAME%

Arguments handling in a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0009.html

Each argument passed to BAT (or CMD) file is accessed with %1, %2, ...

Or use %1 every time and when the processing of the current argument is done then use the command shift to
switch the next argument into %1. The following script accepts a list of files and type each one of them on the
standard output:

[view.bat]

Arguments handling in a batch file 14


Real's HowTo PDF version

@echo off
if "%1" == "" goto error
rem - process each of the named files
:again
rem if %1 is blank, we are finished
if "%1" == "" goto end
echo.
echo Processing file %1...
type %1
rem - shift the arguments and examine %1 again
shift
goto again
:error
echo missing argument!
echo usage view file1.txt view2.txt ...
:end
echo.
echo Done.

Create a file with the name as the current date


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0014.html

Create a file with the current date as filename (ex. 2008-11-08.dat)

echo hello > %date%.dat

With the current date but without the separator "-" (ex. 20081108.dat)

echo hello > %date:-=%.dat

To use the current time we must remove the separator ":" because it's not permitted in a filename. (ex.
20081108220221). Since %time% return also a ",", you can't specified an extension.

echo hello > %date:-=%%time::,=%

If you really want an extension (ex. 2008110822022107.dat), try this

set x=%date:-=%%time::,=%.dat
set x=%x:,=%
echo hello > %x%

Here a better formatted solution (ex. log-2011-06-20_22-46-40,62.txt)

@echo off
setlocal ENABLEDELAYEDEXPANSION

Create a file with the name as the current date 15


Real's HowTo PDF version

set today=!date:/=-!
set now=!time::=-!
set millis=!now:*.=!
set now=!now:.%millis%=!

echo hello > log-!today!_!now!.txt

Since Windows use the short format date as defined the regional settings, you can be in trouble if the current
installation sets the short date format to something different than YYYY-MM-DD.

One way to eliminate the risk is to use WMIC to extract the date information and assign the value into our
own environment variable and use to name our log file (ex. log-2011-06-21_17-17-35.txt).

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC ^Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Se
IF %%A GTR 0 (
SET Day=%%A
SET Hour=%%B
SET Min=%%C
SET Month=%%D
SET Sec=%%E
SET Year=%%F
)
)

if %Month% LSS 10 set Month=0%Month%


if %Day% LSS 10 set Day=0%Day%
if %Min% LSS 10 set Minute=0%Minute%
if %Hour% LSS 10 set Hour=0%Hour%

set now=%year%-%month%-%day%_%hour%-%min%-%sec%
set now=%now%
echo hello world > log-%now%.txt

Set an environment variable from a text file content


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0016.html

Let's say we have the following text file.

[howto.txt]

this is an interesting howto

This batch file will read the given file and set the environment variable content with the file content.

Set an environment variable from a text file content 16


Real's HowTo PDF version

[howoto.cmd]

@echo off
SetLocal EnableDelayedExpansion
set content=
for /F "delims=" %%i in (howto.txt) do set content=!content!%%i
echo %content%
EndLocal

gives this output

> howto.cmd
this is an interesting howto

ECHO "<" or ">" in a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0017.html

Since < or > are special characters for the DOS command interpreter, you can't use them directly,

> echo <test>


Bad syntax

Simply prefix them with the DOS escape character "^"

> echo ^<test^>


<test>

Test if a file exists or not


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/windows-batch-test-if-file-exists.html

Single file

@echo off
if exist c:\temp\2010.pdf (
echo pdf exists
) else (
echo pdf doesn't exist
)

Using a wildcard

@echo off

ECHO "<" or ">" in a batch file 17


Real's HowTo PDF version

if exist c:\temp\*.pdf (
echo pdf exists
) else (
echo pdf doesn't exist
)

Single line

if exist c:\temp\2010.pdf echo file exists

if not exist c:\temp\2011.pdf echo file doesn't exist

Touch a file
Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-touch-a-file.html

This one-liner will change the date of a file.

copy myfile.txt /B+ ,,/Y

To touch all files given a wildcard

for %i in (*.pdf) do copy %i /B+ ,,/Y

If used in CMD file then you must double the "%".


touch.cmd

for %%i in (*.pdf) do copy %%i /B+ ,,/Y

For a Java solution, see this HowTo.

Quickly delete files


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-quickly-delete-files.html

Windows doesn't perform very well with a folder containing several thousands of files, especially on a
network.

The performance is not very good if you have thousand of files.

Test if a file exists or not 18


Real's HowTo PDF version

A quick way to delete a large amount of files is to open a DOS Shell and type :

del /f/s/q foldername > nul

to delete all the files in foldername. To remove the empty directory structure, type

rmdir /s/q foldername

To delete from the Windows Explorer, use [shift] + [del] to delete without using the Recycle Bin.

Quickly get how many files in a directory


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-quickly-get-how-many-files-in-directory.html

Windows Explorer doesn't perform very well with a folder containing several thousands of files, especially on
a network.

A quick way to get the number of files is to open a DOS Shell and type :

dir /b /a-d foldername | find /c /v ""

To count files in subdirectories, just add the "/s" switch.

J:\>dir /b /s /a-d BACKUP| find /c /v ""


42553

Turn CAPSLOCK on/off from a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-turn-capslock-on-off.html

In this HowTo, we saw how to toggle the CAPS state using the Word.appplication object from vbscript. Since
the required scripting is simple, it's easy to integrate it in a batch file.

set BAT_HOME=%~dp0
echo %BAT_HOME%
cd %BAT_HOME%
echo Set objShell = CreateObject("WScript.Shell") > temp.vbs
echo Set objWord = CreateObject( "Word.Application" ) >> temp.vbs
echo if objWord.CapsLock ^<^> 0 then >> temp.vbs
echo objShell.SendKeys "{capslock}" >> temp.vbs
echo end if >> temp.vbs
echo objWord.Quit >> temp.vbs
cscript //nologo temp.vbs

Quickly delete files 19


Real's HowTo PDF version

del temp.vbs
echo ... do your thing in the batch file

Increment a counter in a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-batch-increment-a-counter.html

We want to generate an output where a counter is incremented.

wrapper.java.classpath.1=../lib/activation.jar
wrapper.java.classpath.2=../lib/commons-digester-rss.jar
wrapper.java.classpath.3=../lib/DirWatch.jar
wrapper.java.classpath.4=../lib/JavaCom.jar
wrapper.java.classpath.5=../lib/mail.jar
wrapper.java.classpath.6=../lib/mydb.jar
wrapper.java.classpath.7=../lib/MyJar.jar

The code :

@echo off
setlocal enabledelayedexpansion
set /A Counter=1
for %%f in (*.jar) do (
echo wrapper.java.classpath.!Counter!=../lib/%%f
set /A Counter+=1
)

Open Windows Explorer on specific special folder


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-open-windows-explorer-on-specific-special-folder.html

From a command prompt :

explorer.exe shell:Libraries
explorer.exe shell:MusicLibrary
explorer.exe shell:VideosLibrary
explorer.exe shell:PicturesLibrary

Complete list at osattack.

See also this HowTo.

Turn CAPSLOCK on/off from a batch file 20


Real's HowTo PDF version

Get desktop path from a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-get-desktop-path-from-a-batch-file.html

From a CMD, we launch a one-liner PowerShell script, capture its output to initialize an environment variable
and we create a textfile on the desktop.

@echo off
SETLOCAL
FOR /F "usebackq" %%f IN (`PowerShell -NoProfile -Command "Write-Host([Environment]::GetFolderP
SET "DESKTOP_FOLDER=%%f"
)
echo Hello World > %DESKTOP_FOLDER%\realhowto.txt
@ECHO %DESKTOP_FOLDER%

Display a popup from a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-display-a-popup-from-a-batch-file.html

The goal is to display a popup, the calling batch file must stop and wait the popup closing.

Using powershell

echo calling popup


powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Form
echo we are back!

Using MHTA

echo calling popup


mshta javascript:alert("rgagnon.com\n\nHowTo!");close();
echo we are back!

Regular CMD

echo calling popup


START /WAIT CMD /C "ECHO rgagnon.com && ECHO HowTo && ECHO. && PAUSE"
echo we are back!

Using JScript

@if (@x)==(@y) @end /***** jscript comment ******


@echo off
echo calling popup

Get desktop path from a batch file 21


Real's HowTo PDF version

cscript //E:JScript //nologo "%~f0" "%~nx0" %*


echo we are back!
exit /b 0
@if (@x)==(@y) @end ****** end comment *********/

var wshShell = WScript.CreateObject("WScript.Shell");


wshShell.Popup("HowTo", -1, "rgagnon.com", 16);

Download a file from a batch file


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-download-a-file-from-a-batch-file.html

Using powershell (v3.0+).

powershell -command "Invoke-WebRequest -OutFile bruce.xml http://rgagnon.com/examples/bruce.xml

If you need more options, an external utility like WGET for Windows is a good choice.

Open a PDF at a specific page


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0003.html

Use a URL like this


http://www.rgagnon.com/examples/realhowto-vbs.pdf#page=5
to open the specified pdf at page 5.

This document from Adobe describes parameters that allow you to open a PDF file using a URL or command
that specifies both the file to be opened plus actions to be performed once the file is opened.

Convert a PS file to PDF or TIF using Ghostscript


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0007.html

PDF
Put this CMD into the root of your Ghostscript installation.

[ps2pdf.cmd]

Display a popup from a batch file 22


Real's HowTo PDF version

rem
rem Convert a Postscript to a PDF 1.4
rem
rem Usage: ps2pdf.cmd input.ps [output.pdf]
rem
@echo off
rem ___________________________SETUP
set GS_HOME=%~dp0
set GSC="%GS_HOME%bin\gsc.exe"
set fileinput=%1
set cmdfile="%GS_HOME%_%~n1.rsp"
if %2/==/ (set fileoutput="%~dp1%~n1.pdf") else (set fileoutput=%2)
rem ___________________________CONVERT
echo -q -dSAFER -dNOPAUSE -dBATCH > %cmdfile%
echo -sDEVICE#pdfwrite -dCompatibilityLevel#1.4 >> %cmdfile%
echo -sOutputFile#%fileoutput% -f %fileinput% >> %cmdfile%
%GSC% @%cmdfile%
rem ___________________________CLEANUP
if exist %cmdfile% erase %cmdfile%

To convert a PDF to Postscript, see this HowTo.

TIFF
Put this CMD into the root of your Ghostscript installation.

[ps2tif.cmd]

rem
rem Convert a Postscript to a TIFF(s) single-page
rem
rem Usage: ps2tif.cmd input.ps [output.tiff]
rem
rem ___________________________SETUP
set GS_HOME=%~dp0
set GSC="%GS_HOME%bin\gsc.exe"
set fileinput=%1
set cmdfile="%GS_HOME%_%~n1.rsp"
if %2/==/ (set fileoutput="%~dp1%~n1%%d.tiff") else (set fileoutput=%2)
rem ___________________________CONVERT
echo -q -dSAFER -dNOPAUSE -dBATCH > %cmdfile%
echo -sDEVICE#tifflzw -r600 -dTextAlphaBits=4 >> %cmdfile%
echo -dGraphicsAlphaBits=4 >> %cmdfile%
echo -sOutputFile#%fileoutput% -f %fileinput% >> %cmdfile%
%GSC% @%cmdfile%
rem ___________________________CLEANUP
if exist %cmdfile% erase %cmdfile%

Convert a PDF to Postscript using Ghostscript


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-convert-a-pdf-ps-using-ghostscript.html

Convert a PS file to PDF or TIF using Ghostscript 23


Real's HowTo PDF version

Ghostscript is an interpreter for the PostScript language and for PDF.

gswin32c.exe -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=mydocument.ps mydocument.pdf

To convert a PS file to PDF, see this HowTo.

Convert PDF to TIF (TIFF) using Ghostscript


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/convert-pdf-to-tiff.html

Using Ghostscript.

gswin32c -q -dNOPAUSE -dBATCH -sDEVICE=tiffg4 -r300x300 -sOutputFile=test.tif test.pdf

Note : Replace gswin3c for gs in Unix.

The resulting TIF is a little bit bigger than the original PDF. You play with the "-r" (resolution) to achieve a
better look while keeping the size reasonable!

The above command line will produce a single tiff with multiple pages.

To produce one TIFF for each PDF page :

gswin32c -q -dNOPAUSE -dBATCH -sDEVICE=tiffg4 -r300x300 -sOutputFile=test-%03d.tif test.pdf

The resulting TIF files will be named : test-0001.tif, test-0002.tif, ...

Note : In a Windows command file, you need to double the % , -sOutputFile=test-%03d.tif should be
-sOutputFile=test-%%03d.tif.

Merge PDF's (with Ghostscript)


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0015.html

gswin32 -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=Merged.pdf -dBATCH 1.pdf 2.pdf 3.pdf

To merge all the PDF's in a directory, you need two BAT files : [merge.bat]

@echo off

Convert a PDF to Postscript using Ghostscript 24


Real's HowTo PDF version

gswin32 -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=merged.pdf -dBATCH 1.pdf


FOR %%Z IN (*.pdf) DO IF NOT %%Z==1.pdf IF NOT %%Z==merged.pdf IF NOT %%Z==merged2.pdf call mer

[merge2.bat]

@echo off
gswin32 -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=merged2.pdf -dBATCH merged.pdf %1
del merged.pdf
ren merged2.pdf merged.pdf

Ref : Merging PDFs

Ghostscript

Hide information in your email address


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0002.html

You can use an address like this:

[email protected]

the mail will still be delivered to

[email protected]

but the presence of the -tag will tell where your address is coming from!

For example, when posting to Usenet, you can use

[email protected]

and if you receive SPAM using that address, you can be sure that the SPAMMER got your address by parsing
Usenet postings!

Google "little-known" features


Current version of this HowTo :
http://www.rgagnon.com/gp/../gp/gp-0006.html

You can use Google as a web-based calculator.

Merge PDF's (with Ghostscript) 25


Real's HowTo PDF version

Enter 40 + 2 and Google will answer 42 !. The Google calculator supports hexadecimal notation with the
prefix 0x, try it here

Google s calculator also handles conversions.To convert 0x2e in decimal. Like to convert 1 metre in feet.
Google is multi lingual system, try it in French!

Google as an online dictionary to look up any word. All you have to do is enter the keywords what is in your
query, followed by the word in question. If you want to know what is architecture. Another way is to use the
Google keyword define.

Google has pre-defined facts and you can get them with the right query :

• Quebec population
• John Wayne birthplace
• John Wayne birthday
• John Wayne death

Google can be used to find and display current weather conditions, mostly for American location like Detroit.
You can substitute the city name for a zip code.

What is the code for a particular airport, just aks Google !

If you have an area code and want to know which city it serves, just enter the area code; Google will return
the city in which that area code resides.

Looking for MP3 ? Try a search like ?intitle:index.of? mp3 bob marley . But beware some returned sites or
files can be fake.

Written and compiled Réal Gagnon ©2015 [email protected]


http://www.rgagnon.com

Google "little-known" features 26

You might also like