Create a simple batch file that extract, install and more - batch-file

One of my daily task at work, is to extract the content from a downloaded ZIP FILE into a USB STICK drive that must be quickly formatted in FAT32.
After I extract the ZIP File into the USB STICK, there is one file in particular (called setup.bat) that I need to right click and select Run as Administrator.
The final step is to eject the USB STICK from the computer and give the USB STICK to a sales person.
Now my question is, can I create a batch file that does this job for me? I insert the USB STICK drive into the machine and I run the BATCH FILE, everything can be done automatically?
Step #1
Insert the USB Stick (Of course this is a manual step from me.)
Step #2
Run the batch file that we create.
Step #3
The batch file executes: Quick format the USB Stick in FAT32
I do not need to give a name to the volume. It can be empty.
Step #4
The batch file executes: Extract the content from the ZIP FILE located into the downloads folder into the USB Stick.
(The name of the zip file is: plc-stick_8.3)
Step #5
The batch file executes: Run as Administrator a specific file: setup.bat
This is a file located within the package that has been extracted from the zip file into the USB Stick.
Step #6
The batch file executes: Unmount/Eject the USB Stick
Thank you so much in advance for your help and have a beautiful day
sambul35
thank you so much for your help. It is almost done and perfect. I only received a couple of warning message. I am pretty sure this is something that I am missing from your conditions. Any suggestion what I am doing wrong? You can read the execution below. Thank you so much again.
The type of the file system is FAT32.
QuickFormatting 1.9 GB
Initializing the File Allocation Table (FAT)...
Format complete.
1.9 GB total disk space.
1.9 GB are available.
4,096 bytes in each allocation unit.
490,432 allocation units available on disk.
32 bits in each FAT entry.
Volume Serial Number is 2495-4F8F
Waiting for 0 seconds, press a key to continue ...
Unpack completed. Running setup...
The system cannot find the path specified.
'bootinst.bat' is not recognized as an internal or external command,
operable program or batch file.
Install completed
'removedrive' is not recognized as an internal or external command,
operable program or batch file.
All tasks done. Remove Flash Drive.

The batch below performs all the tasks you need. It makes several assumptions:
the USB Thumb drives you process are preformatted at factory with one existing partition
thumbs are always automounted upon hookup to the same drive letter D: . You can change
the drive letter in the script
you downloaded, unpacked and copied to this batch directory
RemoveDrive tool. Its the best way to eject a USB flash drive
from Cmd
you didn't move your user account Downloads folder from its default
location
save this AutoFlash.bat in your user account accessible directory,
create a desktop shortcut to it, select in its
Properties-Shortcut-Advanced option "Run as Administrator"
If these conditioned are met, hook up a USB Thumb, wait until its accessible in Windows Explorer, then run this script by the shortcut to auto perform all your tasks:
<!-- : Begin batch script
#echo off
setlocal EnableExtensions EnableDelayedExpansion
cd /d %~dp0 & set "drive=D:" & set "mount=0" & echo/
set "file=%USERPROFILE%\Downloads\plc-stick_8.3.zip"
if exist %drive%\nul (format %drive% /q /fs:FAT32 /Y /v:USBFlash
) else (set "mount=1" & echo Flash drive is not mounted)
timeout 3
if not %mount% equ 1 (echo/
cscript //nologo "%~f0?.wsf" "%file%" "%drive%\"
echo Unpack completed. Running setup... & echo/
call %drive%\setup.bat
timeout 3 & echo Install completed & echo/
removedrive %drive% -L
echo All tasks done. Remove Flash Drive.
) else (echo/ & echo Reinsert the drive or open Disk Management)
timeout /t 3 /nobreak >nul
exit /b
----- Begin wsf script --->
<job><script language="VBScript">
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set DestFldr=objShell.NameSpace(Ag(1))
Set SrcFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
</script></job>
Let me know if there're any problems running the script.

Related

Open, wait, save, close, and copy a file using Windows batch file commands

With my .bat I would like to:
open the xlsx file,
waiting 2 min,
close the file with save options
copy this file to another folder.
For now I can copy and paste the file, but I don't know how to open it, with a cmd function, and save it.
Thank you for your help.
My code is :
#echo off
cmd "O:\XXXX\*.*"
xcopy/y "O:\XXXX\*.*" "O:\XXX\"
pause
Marie (TooLong;ToRead) in disjointed comments
I suggested, A simpler alternative method to do what you need on this
occasion is to use a simple command line tool see Orlandos Sendkeys
Utility (the example is almost what you want to do)
download sendkeys from cpap.com.br/orlando
see how the demo runs
open excel with a blank sheet and at a CMD> run this demo string
SendKeys.exe 1.5 10 "Microsoft Excel" "Hello!~{PAUSE 2}After 2s.~{PAUSE 2}%(FS)~"
adapt to your own version of excel keys since the %(FS) is ALT File Save in English
you replied
#KJ Thank you, KJ, unfortunately I can't download Orlando with my PC.
So we continue to doing it in a more dirty fashion, but you still need a means to save the file by invoking an autosave which would most easily be done using an extended excel macro in your source .xlsm, anyway
after all these changes your non working file should now be replaced in your question as
#echo off
start "Excel Running" /MIN EXCEL.EXE "\\XXX\Fichier.xlsm"
REM add a delay of **2 minutes !** whilst sheet recalculates before saving a copy
timeout 120
REM copying a file that has NOT been saved using keys at this point will NOT
REM be what you really need to solve your problem unless you use a macro ?
REM see Later
xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\"
REM add a 3 second delay to check above worked but is not really needed
timeout 3
REM temporary for debugging. Later just REM it out
TASKLIST /M |Find /i "exce"
REM this line should be working with either a SUCCESS: or ERROR:
TASKKILL /T /F /IM excel.exe
REM keep this line for seeing errors above, once happy, it can become REM PAUSE
PAUSE
I think that IF you are constrained (by IT policy) to the command line it is best you write your own autosaving macro, however, MY problem is I dont know if you need it for more than one input.xlsm.
So save this as OpenRunSaveExit.vbs in your working folder where your .bat is. There is a reason I did NOT use spaces or & in the name for a later step.
Set WshShell = WScript.CreateObject("WScript.Shell")
' You may need to include the path to excel.exe if it is a portable version like mine
WshShell.Run "EXCEL.EXE "+"\\XXX\Fichier.xlsm", 9
' 120000 milli-seconds = 2 minutes
WScript.Sleep 120000
' These are the English key combinations for ALT+File+Save . SO alter or remove if not needed
WshShell.SendKeys "%FS"
' These are the English key combinations for ALT+File+eXit . SO alter if needed for french excel
WshShell.SendKeys "%FX"
' Lets us wait 2 seconds for clean closure
WScript.Sleep 2000
As Peter has pointed out in his answer you need to /WAIT before xcopy and depending on how your vbs file handling is set-up you may not need Wscript in the start line
NOW replace your .bat with this
#echo off
start /WAIT Wscript OpenRunSaveExit.vbs
xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\"
pause
And check it runs without the need for taskkill.
Finally why use a 2-4 line .bat since a desktop shortcut would potentially be easier to use. So make a shortcut for the .vbs file (right click the .vbs, and in English its Create Shortcut) and wherever it is built move it to your desktop.
Then change the properties like this (where & has a special meaning so the .vbs filename must NOT have spaces or &.)
%comspec% /c "start /wait wscript.exe OpenRunSaveExit.vbs & xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\" & pause"
P.S. I forgot to add Peters start / wait in this image until later
You can't interact with Microsoft Excel (or most of other programs) through Batch unless they provide such an interface. There is however an option to do it with VBS i.e. via an interface Microsoft Excel supports for interacting with that software.
For just opening the program check start command e.g.:
start /B excel.exe <filename>
then you can wait for the user to both edit and save the file for two minutes or also utilize pause if you don't want to introduce a race condition between saving and copying with xcopy.
Alternatively use start like this:
start /WAIT /B excel.exe <filename>
so the opened file blocks the operation and once it closes (no edit or saving by the user guaranteed) then it'll unblock and xcopy would take place without any time-dependent feature.

Printing ZPL file using Batch File Issue

We run NetSuite for our shipping software and use Zebra ZP450 printer to print the thermal label.
The software downloads a .zpl file which I have assigned to run with a batch file, script here:
Net use LPT2: \\%ComputerName%\ZebraFedex
Copy %1 LPT2
Net use LPT2: /Delete
I have installed this on probably 20 or more computers without an issue. But the last two will initiate the batch file but not print.
I was able to hit pause on the batch file and here is what I got:
C:\users\noah\downloads\net use LPT2: \(ComputerName)\ZebraFedex
The command completed successfully
C:\Users\Noah\Downloads\Copy LPT2
The system cannot find the file specified. 0 files copied
C:\Users\Noah\Downloads>Net use LPT2: /Delete
I've checked my file association, which seems correct since I see the command prompt flash on the screen. I have no idea here...
Working successfully on another computer
Problem on puzzling computer
Here's my batch to transfer file to my venerable TLP2844:
#ECHO OFF
SETLOCAL
FOR %%a IN (%*) DO (
IF EXIST "%%a" (COPY /b "%%~a" \\%computername%\TLP2844
) ELSE (
IF EXIST "%%a.txt" (
COPY /b "%%~a.txt" \\%computername%\TLP2844
) else (
ECHO Neither "%%a" nor "%%a.txt" appears to EXIST
)
)
)
where I have a printer called TLP2844 installed as a ZDesigner TLP 2844 device on USB003.
The problem, as shown by the graphics I've included in your question (saves running off chasing links) is that the label file C:\users\melan\downloads\UPSSHIPPINGLABEL1700448.zpl is being provided to the batch as %1 (first parameter). On the problem installation, no filename (presumably C:\users\Noah\downloads\UPSSHIPPINGLABEL???????.zpl is being provided to the batch as %1.
Therefore it's not a batch problem, but a problem with Netsuite.
From your .pdf, on page 26 :
To install a thermal printer driver on a Windows PC:
...
5. In the Share Name field, enter the name of the printer. For example, LP 2844.
The printer name cannot contain spaces.
So you're told the printer name cannot contain spaces, but the example printer name contains a space....Excellent! (shows my level of confidence in the product, but not actually directly relevant to the problem) :(
Personally, I'd change your batch file to
Copy %1 \\%ComputerName%\ZebraFedex
Perhaps you'd try that after fixing the problem where Netsuite fails to deliver the filename to the batch. Perhaps it's set up to produce .pdfs on the computer in question (That's a wild guess)
In response to reply:
Please change your batch file (temporarily for test purposes) to this:
Echo File to print : "%1"
Net use LPT2: \\%ComputerName%\ZebraFedex
Copy %1 LPT2
Net use LPT2: /Delete
PAUSE
which will report the filename supplied by Netsuite to the batch file on the console window, then keep the window open at the end of the batch until the open window receives a keystroke.
Please report results for both a "working" and a "buggy" installation.
Change .bat file like below, replacing the printer share name with your own. Happened on one of our critical computers that is also the host for FedEx/UPS.
C:\WINDOWS\system32\net.exe use LPT2: \\%ComputerName%\Zebra_ZP500_Shipping_FedEx1
Copy %1 LPT2
C:\WINDOWS\system32\net.exe use LPT2: /Delete
Thank you Noah Schultz for the Pause suggestion for batch file, and to QWERTY for article on Net command issue
Reference

Batch Copy Issue

We have an integration engine, which creates txt files for the opposite host system. Our system writes files to local folder. I created a bat file like that and scheduled for every 1 minute:
xcopy /v /y E:\*.txt Z:\
move E:\*.txt E:\Processed (for backup purpose)
Z:\ is the mapping folder of the host system and that folder is being scanned frequently. If a file is processed it will be deleted immediately by the host system.
My problem is, sometimes files are written duplicated. I mean users see the activies as twice. I think that's because of this; consider a moment which the host system processes my file at the same time of xcopy executes and things get messed up. I know it is impossible to happen those at the same time but maybe network lags causing machines to behave like that?
Any ideas?
Thanks
What about using following batch file?
#echo off
set "SleepTimeInSeconds=60"
rem For sleep time using PING command 1 must be added
rem because the first trial is always successful.
set /A SleepTimeInSeconds+=1
:NextRun
echo %TIME% Searching for files to copy and move ...
for %%I in (E:\*.txt) do (
copy /B /V /Y /Z "%%I" Z:\
move /Y "%%I" E:\Processed\
)
%SystemRoot%\System32\ping.exe 127.0.0.1 -n %SleepTimeInSeconds% >nul
goto NextRun
It copies each file separately on the server and then moves the file to the backup directory.
See How to sleep for 5 seconds in Windows's Command Prompt for the sleep time solution using command PING. You could perhaps also use command TIMEOUT depending on version of Windows which would be even better.
This batch file must be started only once on startup of machine and should run forever until shutdown of machine. Don't run this batch file as scheduled task every minute.
The scheduled task starting the batch file every minute caused the problem with processing files twice because if copying and then moving all *.txt files does not finish within 1 minute caused for example by a temporary network problem, another batch process was started doing the same as the still running batch process.

batch file to copy files to C: from USB then run another batch file from c:\temp

For my work I install software and configure it using a batch file; setting folder permissions, copying config files from a server share to make it work etc. All this is fine and I have been using stuff I have got from here for some time with no problem. I have to do it on multiple computers and on occasions at places where the link is so slow it takes ages to run everything from the server share.
I made a batch file that lets me choose between network install process or from USB to really speed things up. However I'm now faced with waiting for everything to finish installing from the USB before I can move on to the next PC. Many of the PC's are very slow so I can be waiting best part of 10 mins. I'd like to be able to run a batch file from the USB which then copies the software installer and related files to C:\Temp (or such) then launch another specific batch file from C:\Temp (and runs from that dir). The end result being I can plugin the USB, run the initial copy to C:\Temp bat file, the called batch file from C:\Temp then does the install instead of USB allowing me to remove the USB and get on with the next PC without waiting for the process to finish from USB.
I have had some success on my PC with windows 10 ( I assume will work fine for 7, 8 etc.) However with XP (which in my line of work still crops up more than you'd think) when I remove the USB stick, the process is trashed because for some reason, even though I call the C:\Temp bat installer in a new window, that new window still holds on to the fact it's coming from USB, there fore it wont complete unless I leave the USB in. Which is not what I want of course. Maybe there is a better way I'm sure, I just need a solution that works on all XP, 7 , 8 etc. You can see, I just copy a few things to C:\Temp then choose which bat installer I need at the time, then (try) and fire up the appropriate bat running from C:\Temp instead of USB letting me move on with out having to wait. Hope some one can advise. Many thanks!!
Here is the bat that copies from USB to C:\Temp
if not exist C:\Temp md C:\Temp
echo F| XCOPY %~dp0silentinstall.exe /y C:\Temp
xcopy /herky %~dp0GUIDES C:\Temp\Guides /i
echo 1 -- Standard
echo 2 -- DelR2
echo 3 -- FullWipeInstall
echo;
set /P rmFunc="Enter a choice: "
echo --------------------------------------------------------------------
for %%I in (1 2 3 4 5 x) do if #%rmFunc%==#%%I goto run%%I
goto begin
:run1
echo F| XCOPY %~dp0Standard /y C:\Temp
cd C:\Temp
call cmd /c Standard.bat
exit
:run2
echo F| XCOPY %~dp0DelR2.bat /y C:\Temp
cd C:\Temp
call cmd /c "DelR2.bat"
exit
:run3
echo F| XCOPY %~dp0"FullWipeInstall.bat" /y C:\Temp
cd C:\Temp
call cmd /c "FullWipeInstall.bat"
exit
Your bat file resides on the USB. So it can't load the exit statement if USB is removed. I suspect that you are just lucky that it works on some OS's because there is nothing to do other than exit anyway. Without testing there are probably several ways to fix:
1. Replace these 2 lines with a suitable START command and then exit. See START /?
cd C:\Temp
call cmd /c "FullWipeInstall.bat"
Put the exit on the call and the exit on the same line like this
call cmd /c "FullWipeInstall.bat" & exit

Batch File running fine if double-clicked but does not run in Windows Scheduled Task

I have an archive.pst file on my C: drive that I use in outlook to backup my email. But my C: is not backed up each night. So I'd like to copy the .pst file to my network drive so it will consistently be backed up. I do not want outlook to open the .pst file directly from the network drive for a variety of reasons.
Therefore I am trying to create a scheduled task that will copy my .pst file to a network location each day. The batch file below works perfectly if double-clicked. If I try to run the scheduled task, only the log file is created. Outlook doesn't close and the .pst file is not copied. I've tried running with the highest privileges but that doesn't seem to help. Any ideas would be appreciated.
cscript.exe close_outlook.vbs
::This is my VBS Script
::Set Outlook = CreateObject("Outlook.Application")
::Outlook.Quit
ping localhost > nul
set idrive="\\myserver\drive\\Outlook Files\"
set current="C:\myfolder\myuser\Documents\Outlook Files"
echo Start Time of Copy: %time% >> %idrive%\Log.txt
copy %current%\archive.pst %idrive%\archive.pst /y
echo End Time of Copy: %time% >> %idrive%\Log.txt
move %idrive%\Log.txt %idrive%\BackupLogs\Log.txt
ren %idrive%\BackupLogs\Log.txt %date:~10,4%-%date:~4,2%-%date:~7,2%_log.txt
cscript.exe open_outlook.vbs
::This is my VBS Script
::set shell = createobject("wscript.shell")
::shell.run "outlook.exe"
EXIT
In reviewing the previous responses, I have shortened the batch file to only the code below. This works when double-clicking, but not when scheduling a task. I've also tried the same task moving the .vbs script to a network drive. Same outcome.
%SystemRoot%\System32\cscript.exe "C:\OutlookBackup\close_outlook.vbs"
%SystemRoot%\System32\ping.exe -n 4 127.0.0.1>nul
%SystemRoot%\System32\cscript.exe "C:\OutlookBackup\open_outlook.vbs"
1. Specify all files in a batch file executed as scheduled task with full path.
Double clicking on a batch file results usually in running the batch file with currently working directory being the directory of the batch file. But when running a batch file as scheduled task, the system32 directory of Windows is the current working directory.
Is close_outlook.vbs and open_outlook.vbs in system32 directory of Windows?
I don't think so. Replace in batch code below Path to\Script File twice by the right path.
2. Assign string values with space to environment variables right.
variable=value is the parameter for command set. With
set idrive="\\myserver\drive\\Outlook Files\"
you assign to variable idrive the value "\\myserver\drive\\Outlook Files\" with the double quotes included. This results on expansion of
echo End Time of Copy: %time% >> %idrive%\Log.txt
in the command line
echo End Time of Copy: 19:21:53 >> 1>"\\myserver\drive\\Outlook Files\"\Log.txt
and this is not right, isn't it.
Correct is:
set "idrive=\\myserver\drive\Outlook Files"
I removed also second backslash after drive and the backslash at end of folder path.
As the environment variable contains now the path with space(s) without double quotes, the double quotes must be added where the value of the environment variable is used concatenated with a file name, see batch code below.
There is one more reason why using "variable=value". A not visible trailing space at end of the line with command set in batch file is also appended to value of the environment variable if double quotes are not used or used wrong. Read this answer for details about correct assignment of string values to environment variables.
3. Define the wait loop using command ping better.
The command
ping localhost > nul
produces a wait. But it is better to use something like
%SystemRoot%\System32\ping.exe -n 4 127.0.0.1>nul
as now the wait is determined with exactly 3 seconds.
4. Do not insert a space left of redirect operators > or >> for stdout.
Why this should not be done was explained by me here in detail.
5. Avoid environment variables not defined in batch file itself or in system account.
Your batch file uses only environment variables defined in batch file itself. So this advice is here not really needed.
However, many batch file working fine on double click but not on running as scheduled task fail because the batch file depends on environment variables like PATH or others which are related to current user account. It is safe to use environment variables which exist for all accounts like SystemRoot.
Reworked batch code
Here is your batch file with the appropriate changes whereby the paths of the two *.vbs files must be set correct by you before the batch file (hopefully) works as scheduled task.
%SystemRoot%\System32\cscript.exe "Path to\Script File\close_outlook.vbs"
%SystemRoot%\System32\ping.exe -n 4 127.0.0.1>nul
set "idrive=\\myserver\drive\Outlook Files"
set "current=C:\myfolder\myuser\Documents\Outlook Files"
echo Start Time of Copy: %time%>>"%idrive%\Log.txt"
copy /B /Y /Z "%current%\archive.pst" "%idrive%\archive.pst"
echo End Time of Copy: %time%>>"%idrive%\Log.txt"
move "%idrive%\Log.txt" "%idrive%\BackupLogs\Log.txt"
ren "%idrive%\BackupLogs\Log.txt" %date:~10,4%-%date:~4,2%-%date:~7,2%_log.txt
%SystemRoot%\System32\cscript.exe "Path to\Script File\open_outlook.vbs"
set "idrive="
set "current="

Resources