Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

701.

Solve : In Batch file how to pass variables?

Answer»

I Created which will open a  website now how to pass ID and password details in the website from Batch file.


-Once logged want to post a  file from my local desktop to Website.

Can some one help me pleaseThat is not going to happen with batch.Have you tried VBScript? Or Powershell? Those languages give you GREAT DEAL more capability, and would be ABLE to service what you are wanting, if in a very end around fashion. THANKS for help...Yha Iam TRYING that .

702.

Solve : Batch file save/load variables?

Answer»

Hey, im having some PROBLEMS finding how to overwrite multiple variables to 1 .bat file with mutiple lines. Basicly im making a small Rpg game and there is a few stats (e.g. strength, health, intellect) that i want to write to one file such as:
set strength=25
set health= 100
set intellect 50
within the main batch file im using the command echo set health=%health%>health.bat, but ideally i want to put all these variables into 1 file. This is where the problem comes in, any ideas how I would go about overwriting say the strength without affecting the others? I thought of using something like:
 FOR /F "tokens=2 delims=," %%G IN (stats.bat) DO echo %%G %%H
and having them laid out with in 1 line with commas separating each variable, but I still cant figure out how to use a command to overwrite the specific one needed and also set that variable into the main file (as I don't want to just echo it).

If there is any more information I have missed or if you need anything clarified just ask,
Thanks in advance.You have more tools available to you by using the WSH instead of just plain batch. Batch is so 1990 ish. It is so retro.
In the search box above enter WSH and find articles that have talked about this before.Well, you would probably have an easier time by reading and writing the stats at the same time. So this: Code: [Select]for /f "delims=," %%A in (stats.bat) do (
  set health=%%A
  set strength=%%B
  ...
)could be used to read your stats and a simple:
Code: [Select]echo %health%,%strength%,...>stats.batto write the stats back. It's easier to do it this way in batch, but as Geek suggested, you may have an easier time doing this in another language.Hey guys, thanks for the REPLY but I'm still having a little trouble with it, first off just wondering in your 2 codes Raven would the first 1 read MULTI line but the second one only save to single line? and when I try the code I get this:

and to reply to Geek-9pm i have never even heard of WSH and most of the game is already created im just working on loading/saving the game now, thanks for the tip though ill be looking it up Quote

and to reply to Geek-9pm i have never even heard of WSH and most of the game is already created im just working on loading/saving the game now, thanks for the tip though ill be looking it up
Sorry I did not explain. Microsoft encourages users to move away from using just batch for non-trivial tanks.
Quote
Windows Script Host
From Wikipedia, the free encyclopedia
  (Redirected from WSH)
http://en.wikipedia.org/wiki/WSH

The Microsoft Windows Script Host (WSH) is an automation technology for Microsoft Windows operating systems that provides scripting capabilities comparable to batch files, but with a greater range of supported features. It was originally called Windows Scripting Host, but was renamed for the second release.
WSH lets you use neither the command line or a windows interface.  It allows you to use other scripts as part of a task.  Even two different languages in the same task. I wish CH would have a WSH area in addition to the DOS area. Many new users don't know that more advanced tools are built-in to current version of Windows. End of Ran t. Pardon me.
settings.ini
Code: [Select]strength=25
health=100
intellect=50ini.bat
Code: [Select]echo off

REM Reading in Property file
for /f "tokens=1,2 delims==" %%G in (settings.ini) do set %%G=%%H

REM echoing the values
echo Strength %strength%
echo Health %health%
echo Intellect %intellect%

REM Changing the values of each
set /a strength+=10
set /a health-=5
set /a intellect-=8

REM echoing the changed values
echo Strength %strength%
echo Health %health%
echo Intellect %intellect%

REM Writing the changes back to the settings file
for %%I in (strength health intellect) do (
setlocal enabledelayedexpansion
TYPE settings.ini | find /v "%%I=">settings.tmp
move /y settings.tmp settings.ini >nul
echo %%I=!%%I!>>settings.ini
)
type settings.iniOutput
Code: [Select]Strength 25
Health 100
Intellect 50
Strength 35
Health 95
Intellect 42
strength=35
health=95
intellect=42Thanks for the reply squash, but I need the stats to be overwritten rather than flooding the file with updated ones. Any idea how I could change your code to achieve this?
Thanks.Settings.ini

Code: [Select]strength=25
health=100
intellect=50

If the loop variable (the line read from file by FOR /F) is of the format variablename=value then you can just put the set keyword in front of it:

Code: [Select]echo off

REM Read settings from file
for /f %%S in (settings.ini) do set %%S

REM Show values stored in memory
echo strength  %strength%
echo health    %health%
echo intellect %intellect%

REM Alter a setting
set /p health="Enter new value for health ? "

REM Write settings to file
echo strength=%strength%    > settings.ini
echo health=%health%       >> settings.ini
echo intellect=%intellect% >> settings.ini

or more compact... choose a unique variable name prefix and then you can use Set to do all the work of writing the values to file with one command.

settings.ini:

Code: [Select]MyVarStrength=100
MyVarHealth=50
MyVarIntellect=65

Code: [Select]echo off

REM Read settings from file
for /f %%S in (settings.ini) do set %%S

REM Show settings now stored in memory
echo strength  %MyVarStrength%
echo health    %MyVarHealth%
echo intellect %MyVarIntellect%

REM alter a setting in memory
set /p MyVarHealth="Enter new value for health ? "

REM Write settings to file
set MyVar > settings.ini


One difference is that after a write to file the variable names in settings.ini will be in alphabetical order of name. Like this...

Code: [Select]MyVarHealth=67
MyVarIntellect=65
MyVarStrength=100


another idea... run counter and last run logger

Initial state of Runcount.log

Code: [Select]MyProgramVarRuncounter=1
MyProgramVarLastRun=First run
Code: [Select]echo off

REM Read values from file
for /f "tokens=*" %%S in (Runcount.log) do set %%S
echo Script has been run %MyProgramVarRuncounter% time(s) Last run date/time  %MyProgramVarLastRun%

REM increment counter
set /a MyProgramVarRuncounter+=1

REM Get date and time into variable
set MyProgramVarLastRun=%date% %time%

REM Write new values to file
set MyProgramVar > Runcount.log
Code: [Select]C:\>Lastrundemo.bat
Script has been run 1 time(s) Last run date/time  First run
C:\>Lastrundemo.bat
Script has been run 2 time(s) Last run date/time  22/01/2012 14:20:15.86
C:\>Lastrundemo.bat
Script has been run 3 time(s) Last run date/time  22/01/2012 14:20:20.61
C:\>Lastrundemo.bat
Script has been run 4 time(s) Last run date/time  22/01/2012 14:20:27.77
C:\>Lastrundemo.bat
Script has been run 5 time(s) Last run date/time  22/01/2012 14:20:30.14
C:\>Lastrundemo.bat
Script has been run 6 time(s) Last run date/time  22/01/2012 14:20:41.33
C:\>Lastrundemo.bat
Script has been run 7 time(s) Last run date/time  22/01/2012 14:22:14.76
Thanks loads for help I should be able to work with that Quote from: Risen91 on January 22, 2012, 05:04:33 AM
Thanks for the reply squash, but I need the stats to be overwritten rather than flooding the file with updated ones. Any idea how I could change your code to achieve this?
Thanks.

You obviously didn't run my code.  If you look at the output you will see after changing the values and rewriting the values to the stats file that the only values back in the file are the original value names with updated stats numbers.  I don't know what you are thinking it is doing. Quote from: Squashman on January 22, 2012, 07:51:46 AM
You obviously didn't run my code.  If you look at the output you will see after changing the values and rewriting the values to the stats file that the only values back in the file are the original value names with updated stats numbers.  I don't know what you are thinking it is doing.

Ahhh, I thought by "output" you meant what would be in the file after the code had run, my apologies and thank you again, Ill have a look into all suggestions and see what code fits best then. Quote from: Risen91 on January 22, 2012, 07:57:29 AM
Ahhh, I thought by "output" you meant what would be in the file after the code had run, my apologies and thank you again, Ill have a look into all suggestions and see what code fits best then.

The OUTPUT of the batch file!!!! You obviously didn't even bother to read the code and SEE THE SIX ECHO STATEMENTS IN THERE AND THE TYPE COMMAND THAT WAS OUTPUTTING WHAT IT NOW IN THE STATS FILE!No need to holler...
703.

Solve : Batch file don't run in open dos window?

Answer»

Hello when i run this batch file I am unable to get it to popupate a list of pst files on the dos window, just brings up a empty dos window.


echo off
CMD
DIR /a /s | find ".pst"


ALSO how do you get this command below to run in the Start -> RUN command line

DEL /f /s /q %temp%1.
echo off
dir /a /s /b *.pst

2.
DEL /f /s /q "%temp%"
Thanks for the help,

Worked!

1.

echo off
dir /a /s /b *.pst
pause

and

2.

Does not work in XP in the Start -> Run window.  ERROR Windows can not find DEL...

DEL /f /s /q "%temp%"

Quote from: wildmanjoe on JANUARY 22, 2012, 07:25:16 AM

Does not work in XP in the Start -> Run window.  Error Windows can not find DEL...

DEL /f /s /q "%temp%"

Sorry... I FORGOT it was the Run box...

cmd /c DEL /f /s /q "%temp%"Awesome! # 2 worked thanks again, last question i promise.

I also want to run this in start -> run

dir /a /s /b *.pst

I did:  CMD /c dir /a /s /b *.pst

But i am unable to figure out how to get it to pause after it generates a list of the PST files, the dos screen flashes and goes away quick. Noticed the pause command is for batch only and I am unable to locate the  " / a b c d e f " commands list anywhere on the net and find pause.

SOURCEhttp://technet.microsoft.com/en-us/library/bb490965.aspx Quote from: wildmanjoe on January 22, 2012, 09:23:35 AM

I did:  CMD /c dir /a /s /b *.pst

But i am unable to figure out how to get it to pause after it generates a list of the PST files


(Please ignore the post above)

I am showing some screen grabs this time... hope you can see them... this is what I typed... as you can see pause is not just for use in scripts.

Code: [Select]CMD /c dir /a /s /b *.pst & pause


You could also use the /K switch with the cmd processor.

cmd /k dir /a-d /s /b *.pst Quote from: Squashman on January 22, 2012, 02:57:05 PM
You could also use the /K switch with the cmd processo.

cmd /k dir /a-d /s /b *.pst

yes, you are right. I thought of this after I posted but you have beaten me...

If you use /k then the there is no need for a pause because the command window will not close. This is better.


Nice! WOW, I was using the K at the end and it was asking me Y/N to run stuff so i didn't go thhat route, thanks again!
704.

Solve : bat file to random open all but 3 files need help set time delay?

Answer»

Code: [Select]echo off
setlocal EnableDelayedExpansion

rem Set your path here:
set "workDir=C:\Users\anto\test"
rem PUSH to your path
pushd "%workDir%"
rem CREATE a vector with all files in your path
set i=0
for %%f in (*.*) do (
   set /A i+=1
   set file!i!=%%f
)
rem Remove a random file from the vector
set /A rdNum=%random%*i/32768+1
set file%rdNum%=
rem Remove a second random file from the vector (not the same)
:remSecond
   set /A rdNum=%random%*i/32768+1
   if not defined file%rdNum% goto remSecond
set file%rdNum%=+
rem Remove a third random file from the vector (not the same)
:remSecond
   set /A rdNum=%random%*i/32768+1
   if not defined file%rdNum% goto remThird
set file%rdNum%=
rem Start the remaining files (all but THREE)
for /L %%i in (1,1,+%i%) do if defined file%%i start "File %%i" !file%%i!
rem Pop back to your path
popd
It works great opens all but 3 random files in the set folder but now i need it to do the same but set a short delay of about 150milisec between it opening each program

help me pleaseTry this in place of your third from BOTTOM line:

Code: [Select]for /L %%i in (1,1,+%i%) do (
  if defined file%%i (start "File %%i" !file%%i!)
  PING 1.1.1.1 -n 1 -w 150 >nul
)
The 150 is your milliseconds of wait time. Adjust there if you want to adjust the time.

705.

Solve : bat files help with strings?

Answer»

Okay, as part of a Utility that I'm making, I want to extract information from a text file. From the following sample:
mod_RedPowerArray=on
mod_RecipeBook=on
mod_IC2=on
mod_Somnia=on

I'd want the script to display

RedPowerArray
RecipeBook
IC2
Somnia

Is there a way of doing this?If EVERYTHING follows the same format, you can use this one LINER to do what you are asking:
CODE: [Select]for /f "delims=_= tokens=2" %%A in (%textfile%) do echo %%A
You'll have to SET the %textfile% variable at an earlier stage or just hardcode it in if it will not change. Remember to use the usebackq option if you need to use quoation marks for the file name.That's great thanks

706.

Solve : Convert string to numeric (for a beginner)?

Answer»

Hi. How do I convert a string to a float? More specifically, I want to convert my algebraic operation to a number of some form (floating point, double).

I'm new to this and have been up and down the reference guide and the forum and can't find the answer.

Thanks.
You havent been able to fnd the answer, because there isnt one.

Batch files can cope with INTEGERS (only just) and that is that. For what you want, Id suggest a real programming languageYes, you use a script that does floating point.
Quote

http://stackoverflow.com/questions/1503888/floating-point-division-in-a-dos-batch
WScript.Echo Eval(WScript.Arguments(0))
You can call this external script from your batch file, specify the expression to be evaluated and get the result back. For example:

echo off
for /f %%n in ('cscript //nologo eval.vbs "10/3"') do (
  set res=%%n
)
echo %res%

Of course, you'll get the result as a string, but it's better than nothing anyway, and you can pass the obtained result to the eval script as part of another expression.
You may wish to do you whole project in WSH.
Quote
Windows Script Host - Wikipedia, the FREE encyclopedia
The Microsoft Windows Script Host (WSH) is an automation technology for Microsoft Windows operating systems that provides scripting capabilities comparable to …
Windows Script Host is distributed and INSTALLED by default on Windows 98 and later versions of Windows. It is also installed if Internet Explorer 5 (or a later version) is installed. Beginning with Windows 2000, the Windows Script Host became AVAILABLE for use ...
http://en.wikipedia.org/wiki/​Windows_Script_​Host
707.

Solve : "start app.bat" - in fullscreen?

Answer»

First of all; hi =)
I've been luring at this forum for a while now, and finally found a question that wasn't answered already.
Or at least I couldn't find it.

Now, can I (inside my batch file) make another batch run in fullscreen without  having it as default?

I know that you can set the properties of a shortcut to run in fullscreen, but I can't seem to "run" the shortcut, it just runs the file it's referencing to. (Obviously )

Basically I want this:
Code: [Select]set /p pass=<password.dat
set /p password=Enter password:
if %pass%==%password% goto correct
start app_here.bat
exit

and to my app_here.bat to run in fullscreen?
I've tried making a shortcut, and starting that, but that doesn't work.
And "start app.bat /MAX" doesn't work either?

Any suggestions? Batch files require the cmd window. This is the window you need to set to full screen.

1. Open a cmd window
2. Right click the title bar
3. Check full screen on the Options tab
4. Save settings

 
try
Code: [Select]mode 200add this to start of bat file Quote from: Sidewinder on September 27, 2008, 04:50:29 AM

Batch files require the cmd window. This is the window you need to set to full screen.

1. Open a cmd window
2. Right click the title bar
3. Check full screen on the Options tab
4. Save settings

 


i did this and now cmd and all bat files run in full screen, but how can i change in back to normal?    Quote from: Fairadir on September 27, 2008, 09:14:31 AM
i did this and now cmd and all bat files run in full screen, but how can i change in back to normal?   
Press ALT + Enter when in the CMD window and reverse the process.Thanks alot for all the comments, but not exactly what I'm looking for.

As said in my first post, I don't want the fullscreen to be default, only for this one .bat file.
Can I do that?

The mode command I've also tried, but again, in just resizes the windows, doesn't make it fullscreen.

Is there a command which starts a process/batch file in fullscreen?
Or someway I can start the shortcut it self, because I can make the one batch I need to run in fullscreen through a shortcut.Hmmmm.....That has been asked many times in the past and the ANSWER has always been the same.
You can't.As mentioned, batch files require the cmd window.

Try setting up the shortcut something like this:

%windir%\system32\cmd.exe /k yourbatchfilehere
 
Right click the shortcut, and check full screen on the Options tab.

  The batch command "reg add HKCU\Console\ /v Fullscreen /t REG_DWORD /d 1" will set every console application, for example cmd.exe, which all batch files are run from. Starting a batch file after that would make it fullscreen. You could use the "call" command for that. Replacing "/d 1" with "/d 0" resets this option.

File1:
reg add HKCU\Console\ /v Fullscreen /t REG_DWORD /d 1
call file2.bat

File2:
echo In fullscreen we are!
pause
reg add HKCU\Console\ /v Fullscreen /t REG_DWORD /d 0

 Just thought I'd bring it up.

    //EmiLI cannot help, but this will sort out any problems with your code:
Code: [Select]echo off
set /p pass=<password.dat
set /p password=Enter password:
if %pass%==%password% goto correct
exit
:correct
start app_here.bat
exit

This will exit even if you type nothing, when before you may have had some problems.I use something close to Sidewinder's solution.

I set a global Environment Variable as follows:
Code: [Select]Varname=Start /max %comspec%  /k batfile.bat
Batfile.bat will contain your script to be run..

Create another bat file (let's call in startup.bat) which contains:
Code: [Select]echo off
cls

%Varname%
When you click to open Startup.bat it will run the ENV Variable %Varname% which opens the command window in fullscreen then runs your Batfile.bat

Of course:
Code: [Select]Start /max Batfile.batmight work as well.

Good luckOMG, devcom is right dudes it is mode 200 but you don't have to put it at the start of the program you can put it in any part of your program, once the person has typed the right pass word in or what ever just put this code into the batch file you want to run.

if exist 'program used to open this one' goto fullscreen
:fullscreen
mode 200
:: continue on from there

Or you could do it this way

if exist 'program used to open this one' mode 200

Just so you know mode does not have to be 200 you can change it to what ever you want it to be, you can fiddle around with it and see the results that you get.

hope that solved your problem,
Tan_ZaI have create an easy way to do that. It's a EXE in C language name screen.exe

He just simulate the TYPING on the KEYS Alt + Enter. It's simply.

505 donwloads at this time. Go on this link if you want to download it :

Link Removed...

It's easy to use. Just place it in the same directory of the Batch file and add this line in the Batch :

Code: [Select]screen.exe
You can use anothe way to do that. You can just copy the EXE in the "System folder" at this link :

C:\Windows\System32

After that you can use this EXE everywhere the Batch file are.

Windows XP only.

P.S. I know this topic is old. So I just wan't to help the english communauty I'm a french guy. And I'm sory if my english is poor.

See you everybody.daym last post in 2008 until this new post... mate the thing is this guy obviously wanted to program in batch and make it him self not use something that sounds so dodgy... even though this is like prob never gonna be SEEN again it was worth noting.

regards,
Tan_Za
708.

Solve : ms DOS portable?

Answer»

Is there ms DOS portable for PC with windows 7?Windows 7 does not tiredly run any DOS programs.
HOWEVER, there is a way to ENJOY some of the old DOS based programs.

These links may be helpful:
http://technet.microsoft.com/en-us/magazine/ff756590.aspx
Optimize How Windows 7 Runs 16-Bit and MS-DOS-Based Programs

http://support.microsoft.com/kb/833146
How to install DOS Virtual Machine Additions to permit ADDITIONAL functionality in an MS-DOS-based virtual machine in Virtual PC 2004DOSBox Portable emulates an Intel x86 PC, complete with sound, graphics, mouse, modem, etc., necessary for running many old DOS games that simply cannot be run on modern PCs and operating systems. While not restricted to games, the emphasis has been on getting DOS games to run SMOOTHLY, which means that communication, networking and printer support are still in EARLY developement.

http://portableapps.com/apps/games/dosbox_portable

709.

Solve : Varuible Help?

Answer»

heh need more help

so i got this:

set v=0

:testy
pause
if v==0 then goto testy
echo v is 1

:event
set v=1


Basically, when I call event I want the goto testy to cancel out, and print the "v is 1"
but when I RUN it, it dosent do anything (this is a simplified version)if %v%==0 goto testy
hmm it seems that still dosent work for some reason...
Heres the code:

Code: [Select]set HASSHINY=0

...

:EXAMINEROCK
cls
if %HASSHINY%==1 goto ALREADYAQUIREDSHINY
echo Something shiny is on the
echo rock, would you like to
echo take it?
echo       (y/n)

set /p text=""
if "%text%"=="y" goto AQUIREDSHINY
goto AQUIREDSHINY
if "%text%"=="n" goto STARTINGAREA
echo Unkown term: %t%!
pause
goto EXAMINEROCK

...

:AQUIREDSHINY
cls
set AQUIREDSHINY=1
echo You obtained a knife blade!
pause
goto STARTINGAREA


Basicilly, it keeps you from doing the EXAMINEROCK function again. Any help? Quote from: 036483 on January 08, 2012, 05:44:05 PM

Code: [Select]set HASSHINY=0

...

:EXAMINEROCK
cls
if %HASSHINY%==1 goto ALREADYAQUIREDSHINY
echo Something shiny is on the
echo rock, would you like to
echo take it?
echo       (y/n)

set /p text=""
if "%text%"=="y" goto AQUIREDSHINY
....................................................
goto AQUIREDSHINY
....................................................
[code]if "%text%"=="n" goto STARTINGAREA
echo Unkown term: %t%!
pause
goto EXAMINEROCK

...

:AQUIREDSHINY
cls
set AQUIREDSHINY=1
echo You obtained a knife blade!
pause
goto STARTINGAREA

That's your problem. Delete the highlighted line. You will always GO to the "ACQUIREDSHINY" no matter your ANSWER in it's current state. There are a lot of other small issues with this code. It looks like you might want to PROOFREAD it yourself and think about what it is you are trying to accomplish.ugh thats not the problem, that was just some PASTING issue, but something is wrong with the HASSHINY variable thing.A couple of things:

You don't clear the text variable each time, meaning that it will retain its value if the person just hits enter.

Code: [Select]echo       (y/n)
set text=
set /p text=
if "%text%"=="y" goto AQUIREDSHINY
if "%text%"=="n" goto STARTINGAREA
echo Unknown term: %text%!
Also

Code: [Select]set AQUIREDSHINY=1
should surely read

Code: [Select]set HASSHINY=1
oh thanks I didnt see that.
710.

Solve : all mac in LAN?

Answer»

we have 2 workgroup in win network (workgroup and callcenter)

first of all i am listing pc using net view /DOMAIN:workgroup and  net view /domain:callcenter

and ping it to find ip and MAC

callcenter pc name is like

\\Agent-1
\\Agent-2
..
..
\\Agent-100

i can find a pc MAC  usign this command nbtstat -a Agent-1

1- how can i find all pc mac usign just one command ?
2- i can print it into text file like command > c:\conf.txt. how can i do it for all pc at one timeTry this short piece of code:
Code: [Select]echo off
setlocal enabledelayedexpansion

for /f "delims=" %%A in ('net view /domain:workgroup') do (
  SET COMP=%%A
  set comp=!comp:~2!
  nbtstat -a !comp! >>MAC.txt
)
If you are wanting to have a specific output that is maybe only one or two lines per entry, it will require some additional work, so LET us know if that is what you are wanting.first of all

fetching mac all pc in workgroup in one go Quote from: zodehala on February 04, 2012, 02:47:03 AM

first of all

fetching mac all pc in workgroup in one go
Ummm... What?
711.

Solve : formatting an HDD and installing windows in command prompt?

Answer»

Hello good people
i am trying to format my master hard disk in command prompt(it is the only one on my netbook anyway). After formatting i would like to instal windows 7 starter on it. Could any one please provide some help. Even a link to a nice tutorial would do. thnxWindows 7 is often installed from a bookable DVD.
Bit installation over a network can be more INVOLVED. Whenever  there are many DESKTOP PCs to RECEIVE Windows 7 in a COMMERCIAL nor campus environment, special tools are put in PLACE on the network server.

Have you read this?
Installing and reinstalling Windows 7
Follow the links on the above page for specific information.Your best option is to install from USB. 

1) Take your Windows 7 Starter DVD and create and ISO file from it on a working computer.
2) Download the Windows 7 USB/DVD download tool and install it onto a working computer.
3) Find a USB stick that is at least 4GB and plug it into a working computer.
4) Run the Windows 7 USB/DVD tool. This will create a bootable USB stick to install Windows 7 from.
5) Put the USB stick in your Netbook and make sure the USB is set as the first boot device.You cannot deleye Windows from a command prompt as Windows is running...this is bu design...
At boot time using Win7 there is an option to delete and re-create the partition...which wipes all data...

Clean Install of Win7...

712.

Solve : Batch file to Delete Dates from pdf files?

Answer»

Hi All,

I have a list of pdf files in my directory as follows
BAT-109 DDR 01-Jan-12.pdf
BAT-109 DDR 02-Jan-12.pdf and so on,

Could anyone please help with a batch file to delete or rename these files so I could have
the following;
BAT-109 DDR
BAT-109 DDR e.t.c

Please note, I have 50 of these files, date format is constant, but doesn't necessary have to be Jan, it could be Feb as well

Thanks
I would have thought we have given you enough teaching already on STRING replacement to do this yourself.

It easy enough to strip the back end off because you are saying the date format will always be constant.

So in the for loop you can substring the variable to %filename:~0,-9%

but like always you have not clearly defined the parameters to get to your final solution.  If I strip the date off of your two examples they will both have the same name.  You can't rename the file to the name of a file that already exists.  So what are we to do with the 2nd file? Quote from: Squashman on January 12, 2012, 03:31:57 PM

I would have thought we have given you enough teaching already on string replacement to do this yourself.

You tell him, Squashman!
Quote from: Squashman on January 12, 2012, 03:31:57 PM
You can't rename the file to the name of a file that already exists.  So what are we to do with the 2nd file?

Very true, within the same folder. If, perhaps, this is going to go through different folders, it's possible to have same names in different folders. But as mentioned, again, we require more information in order to give you the best possible answer. Quote from: Squashman on January 12, 2012, 03:31:57 PM
have the same name.  You can't rename the file to the name of a file that already exists.  So what are we to do with the 2nd file?


The second file is in a different folder. I would try and be explicit now. I do have a code which I run in different folders to prefix pdf files with dates.
I have this script in each folder so folder 12 it will prefix the files with date 20120101

echo off
pushd C:\Aug\12
::for /f "tokens=*" %%a in ('dir /b /a-d')
for %%a in (*) do rename "%%a" "20120101   %%a"
popd

this will result in the following for example

 20120101 ACA 811 DDR63 03-01-2012.pdf
 20120101  TULIPA-2_DDR_85_030112.pdf
 20120101  BAT-109 DDR 01-Jan-12.pdf
 
I would like to add to the above code so the dates are removed. Apologies Squashman, the dates aren't constant and are in the formats seen above.
 I would like to then archieve the result below within each folder;

20120101 ACA 811 DDR6.pdf
20120101  TULIPA-2_DDR_85.pdf
20120101  BAT-109 DDR .pdf

I hope this is clear now......

Many Thanks........I thought Raven gave you a batch file for removing the end date and prefixing a new date at the beginning of the file already.Because of the inconsistent dates, and the inconsistencies in the names, it's really not possible to do this WITHOUT some sort of manual oversight. See this POST for the rename program that I built a little while ago. It will allow you to crop out what you want to keep from the old file name and will add a standard beginning name, if you want, or, at the very least, allow you to have a standard naming convention that we can then do a much simpler code to in order to get everything to work out how you want it to work out.

Try the program on a test directory a few times first so that you can see what the feel of it is, and then when you are comfortable with it, run it on the directory you want to run it on. You could probably use it to get the standard beginning you are looking for depending on the folder if you set up a .txt file named "targetdirectory.txt" and place it in the same folder as the program with the target folder you are wanting to affect in there.I THINK by now, 50 files could have been renamed by hand.
713.

Solve : freedos 1.1 and some questions?

Answer»

I have installed freedos to virtualbox for playing with the os at my spare time.  I have some question and want to ask about.

1.I want to change background and foreground color of the screen but i dont know how. Of course if it possible.

2. I am trying to copy whole folder from ONE place to another but for example if i enter c:\> xcopy apple c:\fruit\red   it is only copying inside apple folder and puts them into the red folder. It is not copying whole things with apple folder. Any idea ?

3. Is there an option in dos to make cut and paste with commands.

Thanks for your replay......When using XCOPY it is easier if you are inside the source directory.

You might allso what to see DOS-on-USB from CNET
Quote

DOS-on-USB lets you install MS-DOS 7.1 on your USB memory key. After formatting your flash drive, you can install a FULL working version of MS-DOS to let you run games or system UTILITIES. The best THING about having a DOS-bootable memory key is you can boot into it on any computer, just like a CD.

You'll find this utility great for times you need to do system maintenance, because you wont constantly have to burn a new CD, just copy the program to the USB Drive. With the DOS prompt, you can even install Windows 95 or 98. Recommended USB drive size: 16MB - 2GB. Version 2 features an auto launch for ease of the DOS operating system.
...
Read more: DOS-on-USB - Free software downloads and software reviews - CNET
Download.com http://download.cnet.com/DOS-on-USB/3000-2094_4-10795476.html#ixzz1jNNBuFNO
Thanks for your advice......
714.

Solve : Batch files to delete files and folders?

Answer»

I need a batch file to delete particular folders like
C:\windows\Temp

When i say this, I dont WANT the TEMP folder to be deleted by all the contents of it. I mean all the data inside it including FILES and folders.

Please help.Do a change directory to C:\Windows\Temp
Then USE the remove directory command to remove the directories.
Then use the delete command to remove the files in the TEMP directory.

Code: [Select]rd /s /q c:\windows\temp
md c:\windows\temp
See, it got executed using this code.


For /D %%I in (D:\test\*.*) DO RD /s /q %%I
Del /F /Q /S D:\test\*.*

However I am unable to use this when there is a space between the path like D:\test\pratik MEHTA

In the above path there is a space between the folder name PRATIK and MEHTA. Hence it doesnt execute. Please provide a resolution. Quote from: Pratik_23 on January 18, 2012, 09:20:42 PM

See, it got executed using this code.


For /D %%I in (D:\test\*.*) DO RD /s /q %%I
Del /F /Q /S D:\test\*.*

However I am unable to use this when there is a space between the path like D:\test\pratik mehta

In the above path there is a space between the folder name PRATIK and MEHTA. Hence it doesnt execute. Please provide a resolution.

"Quotes"
Code: [Select]For /D %%I in (D:\test\*.*) DO RD /s /q %%I becomes
Code: [Select]for /d "usebackq" %%I in ("D:\test\*.*") do rd /s /q %%I
Why not use the original code I gave? It seems like a cleaner process than this. Did it run into problems?It didnt run into the problems but as my destination path folder has a space in it like

C:\test\PRATIK MEHTA\abc

now in the above path there is a space between PRATIK & MEHTA hence the code isnt working. It isnt allowing spaces. Kindly help me RESOLVE that.You have to pute "Quotes" around any path or file name with spaces.
715.

Solve : md multiple folders window 7?

Answer»

Hi all,

does anyone know how to make multiple FOLDERS in the cmd window in sequence i.e "folder 1" to "folder 100"?

ThanksWhat would you need 100 command windows for ? ?

Never mind...i misunderstood. Code: [Select]H:\folders>for /l %I in (1,1,10) do mkdir FOLDER%I

H:\folders>mkdir FOLDER1

H:\folders>mkdir FOLDER2

H:\folders>mkdir FOLDER3

H:\folders>mkdir FOLDER4

H:\folders>mkdir FOLDER5

H:\folders>mkdir FOLDER6

H:\folders>mkdir FOLDER7

H:\folders>mkdir FOLDER8

H:\folders>mkdir FOLDER9

H:\folders>mkdir FOLDER10

H:\folders>dir /ad /b
FOLDER1
FOLDER10
FOLDER2
FOLDER3
FOLDER4
FOLDER5
FOLDER6
FOLDER7
FOLDER8
FOLDER9Many thanks you saved me!

I also added in quotes the name of the folder

i.e do mkdir "MYFOLDERNAME%I"

to rename them while they were created which was also a time saver

But what does (1,1,10) MEAN? I guess it means 1 to 10 but what is the other digit for?
Quote from: oh-dear on January 19, 2012, 11:04:20 AM

But what does (1,1,10) mean? I guess it means 1 to 10 but what is the other digit for?

You can take a look at the full documentation by typing in for /? Essentially, when using the /l switch, the first number describes the start point, the last number the end point, and the middle digit designates by how much the step is. So (1,1,10) will end up throwing 1, 2, 3, 4...10, while (4,2,16) will throw 4, 6, 8, 10...16. That's the basic explanation.I thought so, just wanted to check.

Last question on this TOPIC is; what if I wanted to use A to Z instead of numbers for example Appendix A, B, C etc.

thank you for all your help I'm not sure how this works with batch, but I know how to do it with VBScript. In fact, this works great with a hybrid script. See below:

Code: [Select]echo off
setlocal enabledelayedexpansion

echo dim oArgs >ASCII.vbs
echo set oArgs=wscript.Arguments >>ASCII.vbs
echo wscript.echo CHR(oArgs(0)) >>ASCII.vbs

for /l %%I in (65,1,90) do (
  for %%J in ('cscript /nologo ASCII.vbs %%I') do set end=%%J
  mkdir "Appendix !end!"
)

del ASCII.vbs
exit
This will go from A to Z, so you will have to do some manual math if you want to change the LETTERS that are used at all. Code: [Select]echo off
set "chars=ABCDEFGHIJKLMNOPQRSTUVWXYZ"

setlocal EnableDelayedExpansion
for /l %%a in (0,1,25) do echo !chars:~%%a,1! Quote from: oh-dear on January 19, 2012, 11:04:20 AM
But what does (1,1,10) mean?

(start, step, end)
Quote from: Raven19528 on January 19, 2012, 12:00:48 PM
I'm not sure how this works with batch, but I know how to do it with VBScript. In fact, this works great with a hybrid script. See below:

Did you try it? I tried that code out, I could only make it work if the FOR line that calls the VBSCript has the /f switch, and you can reduce the VBScript to one line, and the convention is that script engine switches such as //nologo have 2 slashes (so cscript or wscript can distinguish between switches intended for the engine and those for the script)

Code: [Select]echo off
setlocal enabledelayedexpansion
echo wscript.echo CHR(wscript.arguments(0)) > ASCII.vbs
for /l %%I in (65,1,90) do (
  for /f %%J in ('cscript //nologo ASCII.vbs %%I') do set end=%%J
  mkdir "Appendix !end!"
)
del ASCII.vbs


in fact you can do it in one line of batch

Code: [Select]for %%A in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do mkdir "Appendix %%A" Quote from: Salmon Trout on January 20, 2012, 12:01:27 AM
in fact you can do it in one line of batch

Code: [Select]for %%A in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do mkdir "Appendix %%A"
Doh!  I just had a Homer moment.  Not sure why I over complicated it. Quote from: Squashman on January 20, 2012, 05:44:51 AM
Doh!  I just had a Homer moment.  Not sure why I over complicated it.

Well, I had one too as you can see.
Quote from: Salmon Trout on January 20, 2012, 05:13:01 AM
Well, I had one too as you can see.

And me makes us Amigos Three.
716.

Solve : Batch file to detect close program and rename.?

Answer»

Hi gents

I'm making a batch file to change a file extension "jogger" to "jogger.pack" Then run an third-party program "runner.exe" that using "jogger.pack" file.
What I got so far:
Code: [Select]ren Jogger Jogger.pack
runner.exe
Pause

While Runner.exe is being use, jogger.pack remain the same. After the Runner.exe closed, I need to change the "Jogger.pack" filename back to just "Jogger" again. The cycle repeat of adding extension, run program, and removing extension whenever the user running the bat file.

I don't know how to detect when "runner.exe" closes to do the remove naming.

If possible, perhaps to write code that remove the extension when user close the bat file command window, .

regardTurn on delayed execution. Otherwise things get out of order. Quote from: Mortifer on February 01, 2012, 12:36:47 PM

I don't know how to detect when "runner.exe" closes to do the remove naming.

Code: [Select]:loop
REM Wait 60,000 milliseconds (1 second)
PING 1.1.1.1 -n 1 -w 60000 >NUL
REM check tasklist to see if runner.exe is running
REM if it is go to :loop
tasklist | findstr /I "runner.exe" > nul && goto loop
REM you get here after runner.exe stops
REM do your rename stuff NEXT
I guess I am confused on this.   Batch files are sequential processing.
It will not go on to the next command until the PREVIOUS one completes.
At least I have never run into an instance of this not happening.
Not sure why you couldn't use the START command with the wait switch either.
So I guess I am not sure why we would need to use tasklist to see if it is still running.
squashman, you have a very good point.

Hi gents

I'm new at this so thank you very much for the speedy response 
The code Salmon provided works superbly.

I tried messing around with Squash Start /wait switch too. However, I later found out that it doesn't work on 32-bit GUI app which "runner.exe" unfortunately is.


Thank you all againWell I am pretty sure Notepad is a 32bit gui application and I have posted examples on this very forum executing notepad with and without notepad and the batch file paused each time until I closed notepad.Well this certainly is INTERESTING.  It is KIND of a mixed BAG of  what applications will wait and which ones will not.
Seems like all the Microsoft apps I throw at it will wait.
Chrome will not.
Firefox waits.
itunes waits
Skype waitsFound a few more things.
http://www.ericphelps.com/scripting/samples/index.htm#Run
You can use the Wait For Title or Wait for Exe VBscripts to pause your script.
Although I guess it really doesn't hurt to do keep polling for the process with Tasklist.  Especially if you want to keep it pure batch.
I tried it on Runner.exe and it won't wait . The wait switch would have been lovely as users might run the program for a large amount of time and i'm not sure what 700+ checks might do to performance.

Ye, VBscript will likely give me a brain aneurysm. Perhaps if i'm 20 years younger I might try to learn it 
The Vbscript is a no brainer to use.  All you do is download it and use.  Nothing to edit inside the code at all.

You would use it just like this.
Code: [Select]ren Jogger Jogger.pack
runner.exe
WaitForexe.vbs runner.exe
ren Jogger.pack Jogger Quote from: Squashman on February 02, 2012, 07:56:19 PM
The Vbscript is a no brainer to use.  All you do is download it and use.  Nothing to edit inside the code at all.

You would use it just like this.
Code: [Select]ren Jogger Jogger.pack
runner.exe
WaitForexe.vbs runner.exe
ren Jogger.pack Jogger
OK. But where is WaitForexe.vbs Quote from: Geek-9pm on February 02, 2012, 08:18:31 PM
OK. But where is WaitForexe.vbs
Quote from: Squashman on February 01, 2012, 09:35:42 PM
Found a few more things.
http://www.ericphelps.com/scripting/samples/index.htm#Run
You can use the Wait For Title or Wait for Exe VBscripts to pause your script.
Although I guess it really doesn't hurt to do keep polling for the process with Tasklist.  Especially if you want to keep it pure batch.
From the link bySquashman
Code: [Select]On Error Resume Next
If WScript.Arguments.Count <> 1 Then
    WScript.Echo "Waits for an application to shut down. Usage:" & vbCrLf & Ucase(WScript.ScriptName) & " ""Program.exe""" & vbCrLf & "Where ""Program.exe"" is the executable name of the application you are waiting for."
Else
    blnRunning = True
    Do While blnRunning = True
        Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
        Set colItems = objWMIService.ExecQuery("Select Name from Win32_Process where Name='" & Wscript.Arguments(0) & "'",,48)
        blnRunning = False
        For Each objItem in colItems
            blnRunning = True
        Next
        WScript.Sleep 500
    Loop
End IfNo quite so simple. The thing giving by Salmon Trout is more simple. Quote from: Geek-9pm on February 02, 2012, 10:03:25 PM
From the link bySquashman
Code: [Select]On Error Resume Next
If WScript.Arguments.Count <> 1 Then
    WScript.Echo "Waits for an application to shut down. Usage:" & vbCrLf & Ucase(WScript.ScriptName) & " ""Program.exe""" & vbCrLf & "Where ""Program.exe"" is the executable name of the application you are waiting for."
Else
    blnRunning = True
    Do While blnRunning = True
        Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
        Set colItems = objWMIService.ExecQuery("Select Name from Win32_Process where Name='" & Wscript.Arguments(0) & "'",,48)
        blnRunning = False
        For Each objItem in colItems
            blnRunning = True
        Next
        WScript.Sleep 500
    Loop
End IfNo quite so simple. The thing giving by Salmon Trout is more simple.
And this is coming from a guy who sits there and recommends PowerShell to people who ask questions about batch files and never provides them a PowerShell script.  Then you see myself, Raven or Salmon come along and write the Batch file that can do it.

I am sure the batch script code from Salmon Trout was not so simple for the O/P to understand either.  I basically said the VBscript was easy to use!  I showed the BATCH code on how to use the VBscript.  How hard can that really be!  You don't have to know VBscript to use the code at all. Just download it and use it in your batch file.
717.

Solve : Attempting to use FOR in DOS .bat file?

Answer»

I have numerous file in the current directory (FILE.1.txt, FILE.1.txt, FILE.3.txt, etc.) and am attempting to use the FOR COMMAND in a .bat file as follows:

   FOR /F %%FILE IN ("FILE.*.txt") DO JAVA -CP .;../. myJavaClass CONSTANT %%~nxFILE %%~nFILE.tmp %%~nFILEout.txt

passing various forms of the filename as parameters to the Java class. Unfortunately, this FAILS with the message:

   %FILE was unexpected at this time.

Thanks in advance for any help you may be able to provide. Quote

%%FILE

FOR variables can only be single letters (A-Z, a-z, case sensitive). Type FOR /? at the prompt to see the documentation.

718.

Solve : Batch file copies to wrong folder on x64?

Answer»

I have a batch file that I converted to exe. It has a line that copies a file like this:

copy filename.dat %SYSTEMROOT%\system32

On windows 7 32-bit, it works fine, but on x64 it copies to the sysWOW64 folder for some reason even though I explicitly specify system32. It causes the file to not work because only system32 is in the path variable and sysWOW64 is not, so it can't be accessed from anywhere. I need to figure out how to force it to copy to system32 (i don't want to mess with the path). I can make it work by manually copying it with explorer, but I need the program to do it.You will need to "mess with the path"...
And check if you are using the 64 or 32 bit cmd.exe. (You did know there are two?) The 32 bit one redirects system32 to SYSWOW64  - read the Wiki about wow64 at http://en.wikipedia.org/wiki/WoW64
 
64 bit... %windir%\system32\cmd.exe
32 bit... %windir%\syswow64\cmd.exe

http://bc-programming.com/blogs/2009/12/windows-x64-fileregistry-redirection/

Basically, your batch file is now being run always as a 32-bit program because the executable is 32-bit and thus it will always be susceptible to redirection. (so either don't convert to a exe, or write a bunch of workaround script to check what the system's bit width is).Thanks BC. Your blog is very helpful. Here is what I wrote from the information on your blog. Will this work (I don't have a system with 7 64 to test it right now)?

Code: [Select]if %PROCESSOR_ARCHITECTURE%==x86 (
copy file.dat %systemroot%\system32
) else (
copy file.dat %systemroot%\sysnative
)
Am I missing something here? The OP has written a batch file and "compiled" it to make a 32 bit executable (WELL, a 32 bit WRAPPER which unwraps the batch and makes cmd.exe (on a 64 bit system, the 32 bit cmd.exe) run it. So he is living in a 32 bit world with a 32 bit sky, and 32 bit birds singing in 32 bit trees. In that 32 bit world, file system direction ensures that the right "system32" folder is "seen" by apps, birds, trees, etc.

In other words this line

Quote

copy filename.dat %systemroot%\system32

is executed correctly.

Why is there any need to penetrate the 64 bit system?

 Because on the x64 system, this line. . .

copy filename.dat %systemroot%\system32

Copies to sysWOW64 and not the real system32 where I need it to. Quote
Because on the x64 system, this line. . .

copy filename.dat %systemroot%\system32

Copies to sysWOW64

YES, I know it does!

Quote from: Linux711 on January 31, 2012, 12:55:13 PM
not the real system32 where I need it to.

Why do you "need" it to?
Because the PATH environment variable only points to system32 and not sysWOW32, so when I enter it into command prompt from anywhere, it doesn't work if it's in sysWOW64. Plus my program is designed to operate from system32, not anywhere else. At this point, you probably want to know what it's for. It is a program that adds an item to the right-click menu of any file. It allows you to delete any file even if it's protected by trusted installer. That's one of the things in 7 that makes my angry because I like to do a lot of system modding and I can't when everything is blocked from deletion by the admin.
if /i "%programfiles%"=="%programfiles(x86)%" (
    REM This is a 32 bit command prompt
    %systemroot%\sysnative\cmd.exe /c copy filename.dat %systemroot%\system32
) else (
    REM This is a 64 bit command prompt
    copy filename.dat %systemroot%\system32
)


Updated comments to be a bit clearer


if /i "%programfiles%"=="%programfiles(x86)%" (
    REM On a 64 bit system this is a 32 bit command prompt
    %systemroot%\sysnative\cmd.exe /c copy filename.dat %systemroot%\system32
) else (
    REM On a 64 bit system this is a 64 bit command prompt
    REM On a 32 bit system this is the only command prompt
    copy filename.dat %systemroot%\system32
)

Updated comments to be a bit clearer (again)


if /i "%programfiles%"=="%programfiles(x86)%" (
    REM On a 64 bit system this is a 32 bit command prompt
    REM So invoke the 64 bit cmd.exe to do the copy
    %systemroot%\sysnative\cmd.exe /c copy filename.dat %systemroot%\system32
) else (
    REM On a 64 bit system this is a 64 bit command prompt
    REM On a 32 bit system this is the only command prompt
    copy filename.dat %systemroot%\system32
)

Thanks for the help. Can't try it right now bc I'm not near my x64 comp. I tested my code and it didn't work so I'm hoping yours will. If it doesn't, I am just going to change my whole program to run in the windows folder instead of system32. I think that will work. Quote from: Linux711 on February 01, 2012, 10:11:24 AM
I tested my code and it didn't work so I'm hoping yours will.



Using exactly the same batch, on:

my 64 bit Windows 7 system the results were

32 bit command prompt: file was copied to C:\Windows\System32 (not C:\Windows\SysWOW64)
64 bit command prompt: likewise

On my 32 bit Windows XP system the result was the file was copied to C:\Windows\System32




My suggested solution exploits the FOLLOWING:

In a 32 bit command environment the environment variable %programfiles% has the same value as %programfiles(x86)%. In a 64 bit environment it does not. WOW64 recognizes Sysnative as a special alias used to indicate that the file system should not redirect the access. Thus a 32 bit command prompt can select the 64 bit version of cmd. exe. Note that 64-bit applications cannot use the Sysnative alias as it is a virtual directory not a real one, and is not seen by 64 bit programs.

719.

Solve : Print and/or Burning files to CD for backup?

Answer»
Hi,
I'm HOPING someone here can help resolve a problem a friend is having with a very old, DOS based, tanning salon program?  The programs is "SunMate v4", that my friend bought in the late 1980's.  A few years after my friend bought the software, the creator passed away, without being able to sell the software.  Before he died, he placed the software on a public domain Bulletin Board so anyone could download and use it free of charge.  The bulletin board was taken down TWO years later (1994, I believe), so all support for the program was lost when the bulletin board went down.

The original program was installed on an old Windows 3.x operating system.  Since upgrading to a newer, Windows 98 Computer, then later to Windows XP Pro SP3, being able to boot and run the program from pure DOS was lost.  The program now RUNS by booting to Windows XP, then starting it by clicking a link that opens the program from the XP DOS Prompt window.  The original installation floppy disks are corrupt (indicates they haven't been formatted - then ask if I want to format them), so we can't reinstall from them.  A few DAYS ago, my friend inadvertently hit a wrong key combination that changed the software back into "Demo" mode.  I've been able to get the program working again, but am not able to get it set up to print records and daily/weekly service activity, or burn them to CD to keep them updated.

I'm hoping someone here can help me get the program set up so she will be able to print and burn to CD, the business records and activity.  I have found a way of printing the records by using a program named "Printfil", but would rather be able to do it directly from the program because of the number of steps it takes to print using Printfil.

I have the program files and even the DOS files ORIGINALLY used for the program if they would help resolve the problem.  Please get in touch if you might be able to help.
Thanks,
disaksenYou need a reliable backup of whatever you have.

As for the floppies, a skilled technician can get the neat off of them. But I have no idea where you would find one. Kind of a lost art. The alignment of the stepper has to be carefully tweaked to allow reading off track data.  Hard to explain in words. Many floppy drives are mus-alined. Don't assume the diskettes are blank.

One method of backup is to use another computer and 'slave'  the  DOS hard rive to a good working computer. The working computer can copy the files to a backup directory.
720.

Solve : DOS command to execute an app and auto load a MDB file?

Answer»

Greetings,

I have app that can be launched on the command line, but requires a the user to chase down a MDB file through a file explorer window.   Is there a way/dos command that can be used in to AUTOLOAD the MDB file.

Example:  C:\Program Files\application.exe {some DOS switch/command} C:\Datagroups\Data1.mdb

Any assistance on this matter WOULD be greatly appreciated

SpanoirdThere is no GENERIC "Dos command" that forces an application to load a file. If a program is written to accept parameters from the command line then you may be able to just pass the filepath and name. Since you have left us to guess what the "app" is, and since mind READING is very hard to do, the best thing you can do is to read the documentation of the program whose name you have hidden by naming it "application.exe", and look for command line options.

721.

Solve : Renaming a bunch of files to remove a "Q" from the name?

Answer»

Hello all.

I have been unable to figure this simple ONE out. I have been out of writing DOS scripts for a while now and am a little rusty.

I have a folder full of files that contain a Q in them and I want to remove the Q.

ie.  sf0000q.ps s/b renamed to sf0000.ps

Rename with a wild card doesn't work and I am stumped.
Any help would be appreciated.

KenThis is not a class assignment?

You can use Excel or some other spreadsheet to Crete a batch file that does that. Is it considered unfair to use another program?

I would recommend SED, but it is not included on Windows systems.

Also, what it there are already other files the would have the same name if it were not for the Q. Who put in the Q and why?

My point is that programming is not about getting some code. It is more about what you are doing. Just removing the Q from a group of files is not so hard. What is hard is the con sequences.What are you talking about a class assignment?

I have an automatic export process from an HP3000 that will send down files every day and I need to rename the files so that I can process them and load them into my Oracle database.

I have been programming in a 4gl language since 1986 and do not use DOS that often.

As for SED, I prefer VI, or VIM to do any editing. Not to mention this is an MS DOS forum, not a UNIX forum.
Don't mind ol' Geek, he's just TRYING to be helpful. If you have been programming in a 4GL language for NEARLY 30 years then you should find Windows command language a breeze. And you would know that SED (and awk for that matter) exist in Windows ports, and that SED is not an "editor" in the same way that VI and VIM are. What OS were you using back in 1986?



KenL, OK.Got it.
If you have a solution in UNIX you can likely use it in most current Windows system as a command to one of the UNIX utilities that have been ported to Windows.
The following is not an endorsement by Microsoft, but as close as you can get:
http://technet.microsoft.com/en-us/library/bb463168.aspx
But the link below is easier to read for me:
http://en.wikipedia.org/wiki/UnxUtils Code: [Select]echo off
setlocal enabledelayedexpansion
for /f "delims=" %%A in ( 'dir /b *.ps' ) do (
set oldname=%%~nA
set newname=!oldname:q=!
ren "!oldname!%%~xA" "!newname!%%~xA"
)

Thank You Salmon Trout?

EXACTLY what I was looking for.


Just a question, what does the SETLOCAL ENABLEDELAYEDEXPANSION do? Quote from: KenL on February 09, 2012, 12:18:15 PM

SETLOCAL ENABLEDELAYEDEXPANSION do?

NORMALLY a batch script is run in 2 phases (1) parse (2) run. At parse time all the variables are expanded. In a FOR loop it would not be possible to assign values to and read values from such variables. Delayed expansion allows expansion of variables at run time. Such variables use ! as the variable name delimiter. This topic is very heavily covered at many web locations, so you will forgive me for not writing an article about it for you.

ok, thanks again for your help.
722.

Solve : need help! need a batch script to delete certain data from a .c file?

Answer»

Hi all,
I need a batch script to delete certain data from a .c file so it needs to be open up with notepad and edited. i have multiply .c files all different names so i was wonder if someone can help me create a script to delete the following from each text file.

Before Script:

ROM_START( appoooh )
ROM_REGION( 0x14000, REGION_CPU1, 0 ) /* 64k for code + 16k bank */
ROM_LOAD( "epr-5906.bin", 0x00000, 0x2000, 0xfffae7fe )
ROM_LOAD( "epr-5907.bin", 0x02000, 0x2000, 0x57696cd6 )
ROM_LOAD( "epr-5908.bin", 0x04000, 0x2000, 0x4537cddc )
ROM_LOAD( "epr-5909.bin", 0x06000, 0x2000, 0xcf82718d )
ROM_LOAD( "epr-5910.bin", 0x08000, 0x2000, 0x312636da )
ROM_LOAD( "epr-5911.bin", 0x0a000, 0x2000, 0x0bc2acaa ) /* bank0 */
ROM_LOAD( "epr-5913.bin", 0x0c000, 0x2000, 0xf5a0e6a7 ) /* a000-dfff */
ROM_LOAD( "epr-5912.bin", 0x10000, 0x2000, 0x3c3915ab ) /* bank1 */
ROM_LOAD( "epr-5914.bin", 0x12000, 0x2000, 0x58792d4a ) /* a000-dfff */

ROM_REGION( 0x0c000, REGION_GFX1, ROMREGION_DISPOSE )
ROM_LOAD( "epr-5895.bin", 0x00000, 0x4000, 0x4b0d4294 ) /* playfield #1 chars */
ROM_LOAD( "epr-5896.bin", 0x04000, 0x4000, 0x7bc84d75 )
ROM_LOAD( "epr-5897.bin", 0x08000, 0x4000, 0x745f3ffa )

ROM_REGION( 0x0c000, REGION_GFX2, ROMREGION_DISPOSE )
ROM_LOAD( "epr-5898.bin", 0x00000, 0x4000, 0xcf01644d ) /* playfield #2 chars */
ROM_LOAD( "epr-5899.bin", 0x04000, 0x4000, 0x885ad636 )
ROM_LOAD( "epr-5900.bin", 0x08000, 0x4000, 0xa8ed13f3 )

ROM_REGION( 0x0220, REGION_PROMS, 0 )
ROM_LOAD( "pr5921.prm", 0x0000, 0x020, 0xf2437229 ) /* palette */
ROM_LOAD( "pr5922.prm", 0x0020, 0x100, 0x85c542bf ) /* charset #1 lookup table */
ROM_LOAD( "pr5923.prm", 0x0120, 0x100, 0x16acbd53 ) /* charset #2 lookup table */

ROM_REGION( 0xa000, REGION_SOUND1, 0 ) /* adpcm voice data */
ROM_LOAD( "epr-5901.bin", 0x0000, 0x2000, 0x170a10a4 )
ROM_LOAD( "epr-5902.bin", 0x2000, 0x2000, 0xf6981640 )
ROM_LOAD( "epr-5903.bin", 0x4000, 0x2000, 0x0439df50 )
ROM_LOAD( "epr-5904.bin", 0x6000, 0x2000, 0x9988f2ae )
ROM_LOAD( "epr-5905.bin", 0x8000, 0x2000, 0xfb5cd70e )
ROM_END



ROM_START( hooppe )
ROM_REGION( 0x14000, REGION_CPU1, 0 ) /* 64k for code + 16k bank */
ROM_LOAD( "epr-5906.bin", 0x00000, 0x2000, 0xfffae7fe )
ROM_LOAD( "epr-5907.bin", 0x02000, 0x2000, 0x57696cd6 )
ROM_LOAD( "epr-5908.bin", 0x04000, 0x2000, 0x4537cddc )
ROM_LOAD( "epr-5909.bin", 0x06000, 0x2000, 0xcf82718d )
ROM_LOAD( "epr-5910.bin", 0x08000, 0x2000, 0x312636da )
ROM_END



I need to delete all the following except for what below. So it should look like what i have underneath once done. the name in the parenthesis  is always different  fyi. Thanks!!!


After Script:

ROM_START( appoooh )
ROM_END


ROM_START( hooppe )
ROM_END

Two questions to start with:

1. Is this:
Code: [Select]ROM_START( appoooh )
ROM_END


ROM_START( hooppe )
ROM_ENDall that is going to be left in the file? (i.e. Is that the entire file you are showing, or only PART of it?)

2. Where did the ( hooppe ) come from? I don't see that anywhere in your starting text.

1. no there more data within the file.  Basically i need to find ROM_START( appoooh ) and delete all the data between ROM_START( appoooh )  and ROM_END and collapse so there near each other like i wrote above. The thing is the words are always different for example  can ROM_START( hooppe ) or something random.



2.  (hooppe) was the last group of lines at the bottom on the original post


i attached  two files that need it to be done. i have about 100 more . also i made these .txt there originally .c

[year+ old attachment deleted by admin]Then try this:
Code: [Select]echo off
setlocal enabledelayedexpansion

for /f "delims=" %%A in ('dir /s /b *.c') do (
  set count=1
  for /f "delims=^( tokens=1,2" %%B in (%%A) do (
    if "%%B"=="ROM_START" (
      set out!count!=%%C
      set /a count+=1
    )
  )
  set /a stopcount=!count!-1
  set printcount=1
  for /l %%D in (1,1,!stopcount!) do (
    CALL set out=%%out!printcount!%%
    (echo ROM_START(!out!
    echo ROM_END
    echo.
    echo.) >>temp.txt
    set /a printcount+=1
  )
  echo del %%A
  echo ren temp.txt %%~nxA
  pause
)
Check the temp.txt file and ensure that the DEL and REN commands line up like you WANT them too, then remove the pause and the last two echos and let her run. I haven't tried this with subfolders, but it did work on the test file that I used within the same folder. It might be as simple as moving the file to the correct location once it is renamed. That would look like this Code: [Select]move %%~nxA %%~dpA and this line would be added in under the REN command before the final closing parenthesis. Run the code as it is first and see if that modification is needed.

Let us know if it doesn't work as expected.nothing happens not sure why. its says continue but it doesn't do anything. But at the the top it says

The system cannot find the file Jr\Downloads\mame\aeroboto.c

it DELETING the data between the lines but  its also deleting everything in the file INSTEAD of only removing only whats between those two lines. otherwise it would be perfect Another method.  Do it is bite size jobs.
A short BAT file removes all line that start withe  "ROM_LOAD"
first try this on a file:
find  "ROM_LOAD" aeroboto.c
OK?
Now try this:
find  /V "ROM_LOAD" aeroboto.c
Did you like that?
Now:
find  /V R"OM_LOAD" aeroboto.c >> aerobot.c2
Will that work for you?
Thing is it has to be after the parentheses and the word in the parentheses ROM_START( appoooh ) is always different. So the appoooh is always different but in each file it always look just lik what i wrote in my first post.

The first code above would be perfect if it didnt delete eveything else in the file because its doing excatly what i need to be done but i need it not to delete everything else in the file.Just looking at your text file examples it looks like we could delete any line that begins with ROM_LOAD, ROM_REGION or ROM_LOAD16_BYTE.theres also ROM_COPY in some  but i was looking throught more the files ands there also other data in alot of the file that between  ROM_START(  ) and ROM_END that need to be deleted as well so it wouldnt work right.
Seems like it would be easier for you to write a C program to do this.
We have a dedicated C programmer on staff.  If there is something we can't do with our data processing software that is very specific we have him write a C program.  And even before that I usually try something with batch but batch is very slow at processing very large files so I will usually resort to having the program written in C.  im going to keep trying to figure something out. i dont know anything about C programming and im new to writing scripts in genral. so hopefully there a way to edit what i have to not delete everytihg else in the text file. thanks for everyone thats been helping meI didn't see your edit. Yes the batch was only going to have the ROM_START in it and would delete everything else. C programming would probably be a more effecient way of doing this, but batch would allow for it to happen, it is just going to take more processing time and it's a lot different code. I'll work on something today that hopefully will get you on the right track.THANK YOU I REALLY APPERCIATE ITHey Raven, here is some code I worked out.  I just wanted to get the code working for one file right now and it seems to work fine.  The reason I am doing it this way was to preserve the blank lines otherwise the FOR LOOP will discard the blank lines.

Just need to wrap another loop around this to iterate all the input files.  I gotta get going for the day.

Code: [Select]echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set _FILE=argus.txt
set _WRITE=ON
FOR /F "USEBACKQ delims=" %%A IN (`TYPE "%_FILE%" ^| FIND.exe /V /N ""`) DO (
  SET "LN=%%A"
  SET "LN=!LN:*]=!"
  IF "!LN:~0,7!"=="ROM_END" set _WRITE=ON
  IF "!_WRITE!"=="ON" ECHO(!LN!>>"%_FILE%.tmp"
  IF "!LN:~0,9!"=="ROM_START" set _WRITE=OFF
)

723.

Solve : Automatic updater?

Answer»

Hey I'm pretty rusty on dos but I had an IDEA the other day and I thought Id share it with you guys to see if it is doable. Basically I have this game that stores client side data. I will be running the sever the clients connect to but I need to DEVISE a WAY to ensure all clients have up to date client data. I have been trying to think of a user friendly way to allow a batch file to trigger before the client to check for updates and download only if the files on the client side are different than those on the server side. Is this possible? If so any ideas?

Seems like it could work. What kind of server is it? My guess is that it is an FTP server. I think it would be nicer to code it as an actual program though, not just a batch because you are adding it to your game.

If you are sure about the batch, look here: http://www.robvanderwoude.com/ftp.php

Otherwise, I would use the wininet.dll API as part of your game.Heh yeah, i looked a LITTLE to messy to do with a batch and I actually ended up routing my updates though dropbox with some quick python work. Thanks for the reply though http://pastebin.com/vqiF5zHE WELL thats the rough draft anyway Ill clean it up a bit hopefully.

724.

Solve : writing a variable to another batch file?

Answer»

Hello Everyone,

I am attempting to write a BATCH file that will create a custom script based on the information gathered in it. I am running into an issue when I try to write a variable to the new script. I am not trying to pass the value, but the variable name itself. This is what I am trying to do:

Code: [Select]ECHO set cur_yyyy=%date:~10,4% >> %userprofile%\Desktop\Upgrade.bat
But when I view the new file it shows up as

Code: [Select]ECHO set cur_yyyy=2012
Is there any way to do change the syntax so that is not read as 2012 when it is passed? Code: [Select]ECHO set cur_yyyy=^%date:~10,4^%>new.batI originally thought that as well, but but the second ^ doesn't apply. I also tried ^^ with no change.

The line simply doesn't show up in the new file.Works for me.
Code: [Select]H:\>ECHO set cur_yyyy=^%date:~10,4^%>new.bat

H:\>type new.bat
set cur_yyyy=%date:~10,4%

H:\>I have to be missing something here. Below is the entire script so far. I did try what you said above, and it worked when I typed it in the cmd window. The part I am having issues with is at the bottom. This is what I changed it to:

Code: [Select]echo off
setlocal ENABLEDELAYEDEXPANSION

REM Timestamp Generator
REM Parse the date (e.g., Fri 02/08/2008)
set cur_yyyy=%date:~10,4%
set cur_mm=%date:~4,2%
set cur_dd=%date:~7,2%

set timestamp=%cur_mm%%cur_dd%%cur_yyyy%



REM Gather input for file locations
REM :MENU1
REM set _intranetDirVer=
REM echo The DEFAULT installation folder for SimplifyIT is C:\inetpub\wwwroot\simplifyIT\
REM set /p _intranetDirVer="Is this the location of your current installation? (yes/no)"


REM IF %_intranetDirVer%==yes GOTO MENU1a
REM IF %_intranetDirVer% NEQ "yes" GOTO MENU1b


REM :MENU1a
set _intranetDir=C:\inetpub\wwwroot\simplifyIT\
REM GOTO MENU2

REM :MENU1b
REM cls
REM echo If not at C:\inetpub\wwwroot\simplifyIT\
REM set /p _intranetDir="where is your installation currently? "
REM GOTO MENU2

REM :MENU2
REM cls
REM set _intranetDirVer=
REM echo The default backup folder for SimplifyIT is C:\Backups\%timestamp%\Inetpub\wwwroot\simplifyIT, where %timestamp% is the current date.
REM set /p _intranetDirVer="Is this location ACCEPTABLE? (yes/no)"


REM IF %_intranetDirVer%==yes GOTO MENU2a
REM IF %_intranetDirVer% NEQ "yes" GOTO MENU2b


REM :MENU2a
set _backupDir=C:\Backups\%timestamp%\Inetpub\wwwroot\simplifyIT
REM GOTO MENU3

REM :MENU2b
REM cls
REM echo If not at C:\Backups\%timestamp%\Inetpub\wwwroot\simplifyIT
REM set /p _backupDir="where would you like to backup to? "
REM GOTO MENU3


REM :MENU3
REM cls
REM set _intranetDirVer=
REM echo The default file repository for new releases is %userprofile%\Desktop\NewRelease\simplifyIT\.
REM set /p _intranetDirVer="Is this location acceptable? (yes/no)"


REM IF %_intranetDirVer%==yes GOTO MENU3a
REM IF %_intranetDirVer% NEQ "yes" GOTO MENU3b


REM :MENU3a
set _newReleaseDir=%userprofile%\Desktop\NewRelease\simplifyIT\
REM GOTO SUMMARY

REM :MENU3b
REM cls
REM echo If not at %userprofile%\Desktop\NewRelease\simplifyIT\
REM set /p _newReleaseDir="where is your new file repository? "
REM GOTO SUMMARY

REM :SUMMARY
cls
echo File Summary
echo.
echo The location of the installation is:
echo %_intranetDir%
echo.
echo The location of the backup is:
echo %_backupDir%
echo.
echo The location of the new file repository is:
echo %_newReleaseDir%
echo.
pause

REM --------------------BEGIN WRITING NEW BATCH FILE------------------------------
ECHO ECHO OFF >> %userprofile%\Desktop\Upgrade.bat
ECHO setlocal ENABLEDELAYEDEXPANSION >> %userprofile%\Desktop\Upgrade.bat
ECHO set cur_yyyy=^%date:~10,4^% >> %userprofile%\Desktop\Upgrade.bat
ECHO set cur_mm=^%date:~4,2^% >> %userprofile%\Desktop\Upgrade.bat
ECHO set cur_dd=^%date:~7,2^% >> %userprofile%\Desktop\Upgrade.bat
ECHO set timestamp=^%cur_mm^%^%cur_dd^%^%cur_yyyy^% >> %userprofile%\Desktop\Upgrade.bat



Now when I run it, I get this in Upgrade.bat:

Code: [Select]ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
set timestamp=^
My bad.  You have to double the parenthesis in a batch file.
Code: [Select]ECHO set cur_yyyy=%%date:~10,4%%>new.batok, that worked! Thanks! Quote from: Squashman on JANUARY 26, 2012, 10:18:13 AM

Works for me.

That was done at the prompt.

You can escape percent signs (%) using a caret (^) at the prompt. In a batch file it is different. You escape a percent sign with another percent sign (to echo one percent sign in a batch, you use two of them)

At the prompt:

Code: [Select]C:\test>echo echo ^%var1^% > test.txt
Output of command typed at the prompt (test.txt):

Code: [Select]echo %var1%
test.bat:

Code: [Select]echo off
echo echo ^%var1^% > test2.txt
echo echo %%var1%% >> test2.txt
Output of batch (test2.txt):

Code: [Select]echo
echo %var1%
Notice that the first echo is blank.

725.

Solve : Changing special characters.?

Answer»

Win XP Home SP.3+

Why does the first part of the script work as expected but the SECOND does not?

Thanks.

Code: [Select]echo off
cls
setlocal enabledelayedexpansion

set line6=now is the time ( for all good ?

:: Change all ( chars in line6 to -.

for /f "tokens=*" %%a in ("%line6%") do (
    set line=%%a
    echo Line=!line!

    set line=!line:(=-!
    echo Line=!line!
)
echo.&echo.

set line6=now is the time * for all good ?

:: Change all * chrs in line6 to -.

for /f "tokens=*" %%a in ("%line6%") do (
    set line=%%a
    echo Line=!line!

    set line=!line:*=-!
    echo Line=!line!
)



As you have noticed, the asterisk is a special character in NT family (cmd.exe) command language. It is used as the multiplication operator in arithmetic. See SET command help by typing SET /? at the prompt. The string replace operation USING SET will fail if the first (or only) character of the search string is an asterisk (or an equals sign).

I can think of 2 possible solutions

(1) Replace characters one by one in a loop

Code: [Select]echo off

set line6=now is the time * for all good ?

REM Set your asterisk replacement here
set "replace=-"

REM Clear an output string and a counter
set "output="
set j=0

REM loop through the string replacing any asterisk with replace
:loop
call set char=%%line6:~%j%,1%%
if "%char%"=="*" set char=%replace%
set output=%output%%char%
set /a j+=1
if not "%char%"=="" goto loop

REM display input and output strings
echo Input  %Line6%
echo Output %output%
(2) Create a temporary one line Visual Basic Script which uses that language's string replace function.

Code: [Select]echo off
REM Create script
Echo Wscript.Echo Replace(Wscript.Arguments(0),Wscript.Arguments(1),Wscript.Arguments(2)) > RepString.vbs

set line6=now is the time * for all good ?

REM Run script using Cscript engine and capture output
for /f "delims=" %%A in ( ' cscript //nologo RepString.vbs "%line6%" "*" "-" ' ) do set output=%%A

REM Show result
echo Input  %line6%
echo Output %output%

REM Clean up
del RepString.vbs


By the way, we are not using MS-DOS here and using the double COLON ( to start a comment line is non-standard and unsupported and will break a script if it is used inside parentheses such as in FOR loops.

Salmon Trout, thankyou.   I have your batch script working perfectly and will now try to integrate it into another script.   I must check for and amend all chars which are invalid in filenames.

Your assistance is very much appreciated.

Also thanks for the warning on the use of double colon instead of Rem.

Betty.You could loop through a BUNCH of the remaining special characters with a FOR Loop.
Code: [Select]For %%I In (^| ^& ^< ^> ^^ + ^( ^) \ / . # $ { } [ ] ' ; : , ? ` ^%% ^") Do Set line=!line:%%I=!

726.

Solve : Rar files by folder and by month to new destination.?

Answer»

I'm looking to create a batch that will take a set of files created in each month/year and rar them to an archive folder, labeling the rar by date and folder path.

Here's the situation - I have a server that has 12 years of ftp files, uploaded to three directories by each user. The user would upload the files every day. Because they were never moved, each folder has thousands of files.

I would like to move the files by month and year, keeping them grouped in an Archive folder of the same structure, for later retrieval if needed.



There are basically 3 variables: , , and .


Examples:

Source: \\networkserver\\\ (50 files Created between 01/01/01 and 01/31/01) 
Dest: \\networkserver\\ARCHIVE\\__01-2001.rar  (containing all fifty files from that month).
Source: \\networkserver\\\ (50 files Created between 01/01/01 and 01/31/01) 
Dest: \\networkserver\\ARCHIVE\\__01-2001.rar  (containing all fifty files from that month).


Source: \\networkserver\\\ (50 files Created between 01/01/01 and 01/31/01) 
Dest: \\networkserver\\ARCHIVE\\__01-2001.rar  (containing all fifty files from that month).
Source: \\networkserver\\\ (50 files Created between 01/01/01 and 01/31/01) 
Dest: \\networkserver\\ARCHIVE\\__01-2001.rar  (containing all fifty files from that month).

Real Example:

Source: \\uploader500gb\mary001\newpdfs\edit001.pdf (345 files created between 01/01/01 and 01/31/01) 
Dest: \\uploader500gb\mary001\ARCHIVE\newpdfs\mary001_newpdfs_01-2001.rar  (containing all 345 from that month and folder of that user).

Source: \\uploader500gb\mary001\reusedpdfs\reused001.pdf (95 files created between 01/01/01 and 01/31/01) 
Dest: \\uploader500gb\mary001\ARCHIVE\reusedpdfs\mary001_resusedpdfs_01-2001.rar  (containing all 95 from that month and folder of that user).

Source: \\uploader500gb\mary001\errors\pdffail001.pdf (11 files created between 01/01/01 and 01/31/01) 
Dest: \\uploader500gb\mary001\ARCHIVE\errors\mary001_errors_01-2001.rar  (containing all 11 files from that month and folder of that user).


IT would group the files into RAR'd archives, repeat for every of every for every within every folder.

I spent the last 6 hours or so looking at how to CHOP up the date of a file to get DOS to recognize it; I've looked at winRar's command line structure to see how to grab files and format the naming convention.. But I'm an OS X guy - I understand bash, I get applescript. I understand how to read DOS batch, and how to write the BASICS, but I've never been good at the FOR command and how to use it to grab only certain files, how to loop, how to apply variables to it...


I'm guessing that I would have to do this in a few steps:


1. Get the folder as a variable
2. Get the folder as another variable
3. Get the and as variables
4. Create the \ARCHIVE\\
4a. Create a _log.txt of archive creation for each folder structure:  "Created rar \ for -"
5. Pass the variables to Win rar:
5a. Grab all files from \\*.* in same and
5b. Create RAR of \ARCHIVE\\_-.rar
5c. Apply errorlevel LOGIC to verify rar creation.
5d. Continue or repeat, based on success or failure
6. Upon success, Delete the files that were placed into the RAR, after completion, to avoid accidental deletion.
6a. Add to log: "Completed rar and deleted original files of \ for -"
7. Stop within 60 days of current date (leaving -60 days of files untouched in each directory)
8. Repeat with next directory, and repeat inside that with each and each and


I'm not asking for a handout - I'd be more that willing to put the pieces together. I just don't know where to start with all this - beyond the outline. I am going to keep looking at how to build this, but I would welcome some pointers on this, and maybe I can get a skeleton of it working?

I'll keep posting my code as I get the pieces in place, but I could really use some help. Thanks in advance!








That is a really tall order, especially for an OS X guy, so good on you for trying to take it on. It would take anyone a little while to build this, but I think I'll give you some basics and then see how you do at putting them all together.

First, you are going to want to map your drives: Code: [Select]net use z: \\networkserver
This allows you to break things up a little easier. To grab the user variable, try this: Code: [Select]for /f "DELIMS=\ tokens=2" %%A in ('dir /s /b z:') do set user=%%A (This will actually grab the last user in the file first, but working backwards is just the same as working forwards so long as it gets done)

To get the Directory variable we can use this: Code: [Select]for /f "delims=\ tokens=3" %%B in ('dir /s /b z:\%user%') do set directory=%%B
The date variables might end up being a little TRICKIER to capture, depending on what your regional date/time settings expand out to. For instance, my date/time settings have the file creation expanding to 11/08/2011 10:24 AM. Obviously we don't care about the time in this instance, but if your date expands differently, it throws the whole thing off. You will need to use setlocal enabledelayedexpansion in order to use this next line to capture the date variables.
Code: [Select]for /f "tokens=*" %%C in ('dir /s /b /o:d') do (
  set datevar=%%~tC
  set year=!datevar:~6,4!
  set month=!datevar:~0,2!
)
One other part to this, testing for the 60 day threshold, can be done as long as you expand out the %date% variable and see how it looks. Mine is like this: Thu 01/26/2012 so in order to test I would need to parse the date variable out and check it with the variables set in the line above.

See how far you get with this, and let us know if you get stuck.Ok, so I think i have a solution in place:

Using WinRar, RoboCopy, and Dos Batch, I was able to do it.




Code: [Select]
ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
cls
 
:: Insert Calls Here
 
 
set client=User1

:: Call (loops)
:: dothis is the process.
:: %client% is the foldr name
:: Example: call:dothis %client% 01-2001 20010101 20010131
:: Example: call:dothis %client% foldrname startdate enddate
 
call:dothis %client% 01-2001 20010101 20010131
call:dothis %client% 02-2001 20010201 20010228
call:dothis %client% 03-2001 20010301 20010331
call:dothis %client% 04-2001 20010401 20010430
call:dothis %client% 05-2001 20010501 20010531
::etc...



:dothis
 
set theorigpath=\\servername\users\ftpFiles\%~1\FromCust\original
set theerrorpath=\\servername\users\ftpFiles\%~1\FromCust\error
set theformattedpath=\\servername\users\ftpFiles\%~1\FromCust\formatted
set thecompletepath=\\servername\users\ftpFiles\%~1\FromCust\complete
 
set theorigarchivepath=\\servername\users\ftpFiles\%~1\FromCust\archive\%~2-original
set theerrorarchivepath=\\servername\users\ftpFiles\%~1\FromCust\archive\%~2-error
set theformattedarchivepath=\\servername\users\ftpFiles\%~1\FromCust\archive\%~2-formatted
set thecompletearchivepath=\\servername\users\ftpFiles\%~1\FromCust\archive\%~2-complete
set thebasearchivepath=\\servername\users\ftpFiles\%~1\FromCust\archive\
 
 
 
Echo -- Making Archive Dirs --
Echo.
mkdir %theorigarchivepath%
mkdir %theerrorarchivepath%
mkdir %theformattedarchivepath%
mkdir %thecompletearchivepath%
Echo.
Echo -- Made Archive Dirs --
 
 
 
Echo ------------------------------
Echo -- Copying %theorigpath% to %theorigarchivepath% for files between %~3 and %~4
 
cd C:\Program Files\Windows Resource Kits\Tools
 
robocopy %theorigpath% %theorigarchivepath% *.* /MOV /MAXAGE:%~3 /MINAGE:%~4
robocopy %theerrorpath% %theerrorarchivepath% *.* /MOV /MAXAGE:%~3 /MINAGE:%~4
robocopy %theformattedpath% %theformattedarchivepath% *.* /MOV /MAXAGE:%~3 /MINAGE:%~4
robocopy %thecompletepath% %thecompletearchivepath% *.* /MOV /MAXAGE:%~3 /MINAGE:%~4
 
 
 
Echo Copied %theorigpath% to %theorigarchivepath% for files between %~3 and %~4 >> %thebasearchivepath%\Log.txt
 
cd C:\Program Files\WinRAR
 
rar a -df %theorigarchivepath%.rar %theorigarchivepath%
rar a -df %theerrorarchivepath%.rar %theerrorarchivepath%
rar a -df %theformattedarchivepath%.rar %theformattedarchivepath%
rar a -df %theorigarchivepath%.rar %theorigarchivepath%
rar a -df %thecompletearchivepath%.rar %thecompletearchivepath%

... IT's not completely automatic, I did have to use excel to mass create the date ranges, but it is working.

727.

Solve : Script to Look for 1 File but Not Another??

Answer»

I need a script that will search folder + subdirs for the existance of 2 files that don't match but contain information that pertain to a certain item, and if it finds 1 but not the other it will do something such as log that it's missing to another file, or email me.  Here is an example of what I mean.

We have a folder called x:\bkgate\node then under each one of these is a folder for a different location such as PZ04060\reports, and in each one of these FOLDERS are files called reg1.ini through reg12.ini, and also files called ClamScanLog_PZ04060_REG1.txt, ClamScanLog_PZ04060_REG2.txt and so on.  I need something that will look for all these files and if it files for example a x:\bkgate\node\pz04060\reports\reg4.ini but it doesn't have a matching ClamScanLog_PZ04060_reg4.ini it will then put an alert such as "4060 reg4 missing clamscan log" into a log file that we can check daily.  I have made quite a few batch scripts that do some pretty cool things but this one I have no clue how to begin, any ideas?You are GOING to want to run embedded for commands to do the searching you are looking for and also USE the delims to differentiate the files. It's more DETAIL work than anything, but if I get a chance, I'll see if I can put together something for you to use.So you have a folder structure like this.

x:\bkgate\node\PZ04060\reports
x:\bkgate\node\PZ04061\reports
x:\bkgate\node\PZ04062\reports

We are always looking at the FOLDERS that start with PZ?

Should be able to do this with two Two FOR Loops.  One nested inside the other.

728.

Solve : Batch File to empty contents of log file but not delete it?

Answer»

Hi,

I have been searching through this forum for a few hours, some great advice on it, I found it very helpful.

I have a program that has a log file for specific alerts.
This log file has the format applogfile120127.log it's name changes every day.
If I delete the log file it doesn't get recreated when a new alert comes in, ( You have to restart the software ) so I would like to be able to delete the contents of this log file but not delete the entire file itself.

Can this be done via a Dos batch file.
My computer is running Win XP Pro

Many thanks

MacAs my log file name changes every day, even if I could clear the contents of all log file in a specific directory it would be great.

Thanks

MacTry this (substitute the actual file name for "filename.log")

Code: [Select]echo. > filename.log

That should work but my filename changes every day. Is there a way around this?Is it POSSIBLE to do a Null on ALL .log files in a directory as the filename is unknown.

If that is not possible if I could read the unknownfilename.log ( but the only logfile in that directory ) and put the last line of that file into a seperate txt file.

Seem like a long way of doing something simple though. the problem is that the file name is unknown as it increments its name every day using the current date. Clearing all log files in the directory should do the job.

ThanksNot quite sure why you would want to clear the contents of a log file.  Isn't the purpose of a log file to capture relevant information that you can go back and look at another day?If you really want to clear the contents of all the log files in a directory.
Code: [Select]echo off
for %%G in (*.log) do (copy /Y nul "%%G")Just to show you that it works
Code: [Select]H:\logfiles>dir /a-d *.log
 Volume in drive H is DATA
 Volume Serial Number is D2F3-49FA

 Directory of H:\logfiles

01/27/12  12:21 PM                16 logfile1.log
01/27/12  12:21 PM                16 logfile2.log
01/27/12  12:21 PM                16 logfile3.log
               3 File(s)             48 bytes
               0 Dir(s)  58,354,429,952 bytes free

H:\logfiles>clearlog.bat
        1 file(s) copied.
        1 file(s) copied.
        1 file(s) copied.

H:\logfiles>dir /a-d *.log
 Volume in drive H is DATA
 Volume Serial Number is D2F3-49FA

 Directory of H:\logfiles

01/27/12  12:24 PM                 0 logfile1.log
01/27/12  12:24 PM                 0 logfile2.log
01/27/12  12:24 PM                 0 logfile3.log
               3 File(s)              0 bytes
               0 Dir(s)  58,354,429,952 bytes freeThanks I'll give that a go later.  The reason I want to clear the logs is because I'm trying to capture a line in it and get it to send an email alert. I can only manage to capture the first line, so I am going to get the log file cleared after every email is sent.We can help you capture a line of text from a log file. That isn't that hard.That worked a treat guys, thanks very much for all your efforts
You are a credit to this forumAnd... won't you prefer just to get the content of the last line That will SOLVE your problem and keep a real log and getting the info you are looking for to email.

Rem Count the number of lines in the file

Set LINES=0
FOR /F "delims==" %%I in (Your_File.log) Do Set /a LINES=LINES+1
REM Get the Last line
More +%LINES% < Your_File.log > Last_Line.txt

Rem Last_Line.txt will have only the last line Quote from: Migxi on FEBRUARY 02, 2012, 06:32:07 PM

And... won't you prefer just to get the content of the last line That will solve your problem and keep a real log and getting the info you are looking for to email.

Rem Count the number of lines in the file

Set LINES=0
FOR /F "delims==" %%I in (Your_File.log) Do Set /a LINES=LINES+1
REM Get the Last line
More +%LINES% < Your_File.log > Last_Line.txt

Rem Last_Line.txt will have only the last line
Two things not quite right about your approach to that. 

1) If you are ALREADY going to to use a for loop to count the lines you might as well just use the For loop variable to assign the lines to a variable.  Then you don't need to use the counter at all.  You are already parsing every line.  Might as well use it to your advantage.
Code: [Select]FOR /F "delims==" %%I in (Your_File.log) Do Set lastline=%%I
2) Using the FIND command is much much much faster at counting the number of lines in a file.
729.

Solve : modifiying the windows regestry?

Answer»

I'm attempting to modify this GUID key with the REG command.

[HKEY_LOCAL_MACHINE\SOFTWARE\Novell\ZCM\PreAgent]
"Guid"="71781f5d31cb454a9ae1307f99dee53e"

I've tried delete, unload and add....
(reg unload HKEY_LOCAL_MACHINE\SOFTWARE\Novell\ZCM\PreAgent "Guid"="" )

no luck

some help would be much appreciated Most of the time, I don't like to see registry editing done via batch. It raises a lot of "why?'s" when I see it. A few things that I do feel I can help point you too though are:

1. Try getting in the habit of using HKLM and the other provided short names for registry editing. It's less typing, and in my experience works a little better when you are dealing with server/client setups.

2. Have you used the reg delete /?, reg unload /?, and reg add /? commands at the cmd prompt. All will give you good information about syntax and usage (which btw, why are you using unload when you are only trying to edit a single key??)

3. When editing one key, reg delete/add works fine. But when editing multiple keys, get in the habit of setting up .reg files and using reg import. It allows for much better CONTINUITY from start to finish, and lessens the chances of corrupting your registry. (If you are looking for an example of how a .reg file should look, try doing a reg export on a known key and reverse engineer from there)

Again, talking about editing registry entries does not give me a warm fuzzy feeling, because I have seen way too often how easily someone who knows just enough to get them in trouble can corrupt their registry and need to completely reload a system. Good luck.Hi

I've tried the reg unload add and the likes with /? but it does'nt give much infos...

I want to erase the "GUID" beacause Zenworks is bugged and it needs to have a little cleanup

I work for two hospitals in QUEBEC city and Novell Zenworks is pushing all the apps the employees need for work

this is what I've tried with add and delete :

C:\Documents and Settings\ssimartf>reg add [HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Z
CM\PreAgent] "Guid"=""

Erreur : Invalid key name

C:\Documents and Settings\ssimartf>reg add HKEY_LOCAL_MACHINE\SOFTWARE\Novell\ZC
M\PreAgent "Guid"=""

Erreur : too many command-line parameters

C:\Documents and Settings\ssimartf>reg delete HKLM\SOFTWARE\Novell\ZCM\PreAgent
 "Guid"=""

Erreur : too many command-line parameters

C:\Documents and Settings\ssimartf>reg delete HKLM\SOFTWARE\Novell\ZCM\PreAgent
/va "Guid"=""

Erreur : too many command-line parameters

C:\Documents and Settings\ssimartf>reg delete HKLM\SOFTWARE\Novell\ZCM\PreAgent
/ve "Guid"=""

Erreur : too many command-line parameters CODE: [Select]echo off
if exist C:\Zenworks\InventoryDelta.xml (
rmdir /s /q C:\Zenworks
del "C:\WINDOWS\novell\zenworks\bin\ZENPreAgent.exe.cfg.state"
del "C:\PROGRAM Files\Novell\ZENworks\conf\DeviceData.*"
del "C:\Program Files\Novell\ZENworks\conf\DeviceGuid.*"
del "C:\Program Files\Novell\ZENworks\conf\initial-web-service.*"
reg delete HKLM\SOFTWARE\Novell\Zenworks /va /f
reg reg add HKLM\SOFTWARE\Novell\ZCM\PreAgent /v GUID /d """" /f
goto end
else (
del "C:\WINDOWS\novell\zenworks\bin\ZENPreAgent.exe.cfg.state"
del "C:\Program Files\Novell\ZENworks\conf\DeviceData.*"
del "C:\Program Files\Novell\ZENworks\conf\DeviceGuid.*"
del "C:\Program Files\Novell\ZENworks\conf\initial-web-service.*"
reg delete HKLM\SOFTWARE\Novell\Zenworks /va /f
reg reg add HKLM\SOFTWARE\Novell\ZCM\PreAgent /v GUID /d """" /f
goto end
)
if exist "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v GinaDLL (
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v GinaDLL /f
goto end
)
else (
goto end
)
:end
exit
now it sais "else" is'nt recognized.....foud out that "else must be putted like this :

Code: [Select]IF EXIST filename. (
del filename.
) ELSE (
echo filename. missing.
)

730.

Solve : stripping info from cmd prog output and adding to text file?

Answer»

Hi all,

I have a reasonably simple batch program which uses SoX to analyse AUDIO files and produces text output in the cmd window for each file.

I'd like to be able to strip a part of that output text and append that to the end of a text file along with the file name of the audio file it is for.



This is the output of the SoX program in the cmd window.

I'm only interested in the line which starts with "RMS lev DB" and i'd like the text file for this example to look like this...

Quote

"M04296 - LET ME BE THE ONE - BLESSID UNION OF SOULS.mp3";-15.94;-15.93;-15.96
"M03671 - WHINEY WHINEY - WILLI ONE BLOOD.mp3";-16.78;-17.03;-16.54

Does anyone know how i could code a batch file to do this?  And if not, does anyone have any other suggestions for how i can achieve what i want?

I guess some sort of regular expression on the output of the SoX program is what i'm looking for.

Any help is appreciated cheers.

NM

[year+ old attachment deleted by admin]You already got a good start on it.  I would use a Nested For Loop and put your SOX command inside that second for loop.
Code: [Select]for %%A in (*.mp3) do (
    FOR /F "Tokens=4,5,6 delims= " %%G in ( 'SOX "%%~A" -n stats ^|findstr /C:"RMS lev DB"') do (
          echo %%A %%G %%H %%I >>myfile.txt
    )
)Thanks for getting back to me about this Squashman.

There is one small problem though, the 3 values (tokens 4, 5 and 6) aren't getting found and passed on to the text file.

The call to the SoX program goes ok and the results of it's analysis print onto the CMD screen but the values are either not getting found or not being passed on correctly.

This line here doesn't get called at all it seems as the filename ( %%A ) isn't put into the text file either.

Code: [Select]echo %%A %%G %%H %%I >>myfile.txt
Any ideas on what the problem might be?

Cheers

NMThere are some console programs output that doesn't play nice with batch file output.  There are even a few MS utilities that you can't use a FOR loop in a batch file to CAPTURE the output.

I tried loading SOX on my computer and I can't seem to get it work.  If you can help me get that installed and configured I could probably figure out the issue with the output from SOX.
This is what I got when I tried to run the same command you were running on a single MP3 file.
Code: [Select]C:\Desktop_from_first_computer\music>sox Slipknot-Before_I_Forget.mp3 -n stats
sox FAIL util: Unable to load MAD decoder library (libmad).
sox FAIL formats: can't open input file `Slipknot-Before_I_Forget.mp3':Hi,

you just need to put the attached dll file into the same folder as SoX

Thanks for your help.

Cheers

NM

[year+ old attachment deleted by admin]Wow!  I have no idea what SOX is doing but you can't capture any of its output.
It won't let you parse the output in a FOR LOOP nor will it redirect its output to a LOG file.
So my original code will not work nor will redirection to a text file like this:
Code: [Select]SOX "Stone_Sour-3030-150.mp3" -n stats 1>Temp.logOk. Not to worry. Not your fault.

I really appreciate you going to all that trouble for me anyway.

Have yourself a "Thanked".

I've got 22,000 files to process so i might just have to write a program to analyse them in Flash

Cheers

NMI think SOX sends its output to stderr and not stdout

Hi Salmon Trout,

Does that mean there might be a way to capture the data afterall?

Cheers

NMTry Googling for "redirect stderr to stdout cmd"I've managed to find the command to reroute the output but i'm not sure when to apply that in the current script i have.

And you were right, if i use the following command...

Code: [Select]SOX "M03671 - WHINEY WHINEY - WILLI ONE BLOOD.mp3" -n stats 2>Temp.log

i get a log file with the information that would usually be shown in the CMD screen, like this...

Code: [Select]             Overall     Left      Right
DC offset  -0.000025  0.000000 -0.000025
Min level  -1.000000 -1.000000 -1.000000
Max level   1.000000  1.000000  1.000000
Pk lev dB       0.00      0.00      0.00
RMS lev dB    -16.78    -17.03    -16.54
RMS Pk dB      -9.06     -9.72     -9.06
RMS Tr dB      -1.#J     -1.#J     -1.#J
Crest factor       -      7.10      6.71
Flat factor     5.61      6.39      5.14
Pk count        48.5        35        62
Bit-depth      29/29     29/29     29/29
Num samples    10.5M
Length s     237.949
Scale max   1.000000
Window s       0.050

so is there some way that i can redirect the info from stderr to stdout so that the tokens and findstring are carried out ok?

Cheers

NM

p.s. i'm basically TRYING to find where i should put the redirect code Code: [Select]2>&1 or how i should rewrite this to make it workI'm almost there.

I'm redirecting the output to a log file then trying to use the FINDSTR command to search through the log file for one specific line but it isn't working exactly as planned and i get every line output to my final file.

Here is my code...

Code: [Select]echo Filename;Total RMS;Left RMS;Right RMS >> RMS_Stats.txt
FOR %%A IN (*.mp3) DO (
    SOX "%%A" -n stats 2>Temp.log
    FOR /F "Tokens=4,5,6 delims= " %%G IN (Temp.log) DO (
          FINDSTR /F:Temp.log /C:"RMS lev dB"
          echo %%A;%%G;%%H;%%I >> RMS_Stats.txt
    )
)
pause

Any advice on what i'm doing wrong?

Cheers

NMSweet, i finally figured it out!!!

Code: [Select]echo Filename;Total RMS;Left RMS;Right RMS >> RMS_Stats.txt
FOR %%A IN (*.mp3) DO (
    SOX "%%A" -n stats 2>Temp.log
    FOR /F "Tokens=4,5,6 delims= " %%G IN ('FINDSTR /C:"RMS lev dB" Temp.log') DO (
          echo %%A;%%G;%%H;%%I >> RMS_Stats.txt
    )
)
pause

Thanks for all of your help guys.

Cheers

NMI was thinking of redirecting stdout to stderr and not a file... like this...

Code: [Select] 2>&1

This way you don't need to use a temp file

Something like this...

Code: [Select]for %%A in (*.mp3) do (
    FOR /F "Tokens=4,5,6 delims= " %%G in ( 'SOX "%%~A" -n stats 2^>^&1 ^|findstr /c:"RMS lev DB"') do (
          echo %%A %%G %%H %%I >>myfile.txt
    )
) Quote from: Salmon Trout on February 14, 2012, 10:45:58 AM
I was thinking of redirecting stdout to stderr and not a file... like this...

Code: [Select] 2>&1

This way you don't need to use a temp file

Something like this...

Code: [Select]for %%A in (*.mp3) do (
    FOR /F "Tokens=4,5,6 delims= " %%G in ( 'SOX "%%~A" -n stats 2^>^&1 ^|findstr /c:"RMS lev DB"') do (
          echo %%A %%G %%H %%I >>myfile.txt
    )
)
Bingo!
Thanks for chiming in!  Got super busy at work this morning.
731.

Solve : Sound card driver, Audio device choice?

Answer»

I've installed DOS 7.1 on a VM (Virtual Machine) after figuring I needed to changed the boot order of the CD-ROM at some point. During the process I didn't really know what sound card driver to choose and knowing my device use AC97, I chose 1 of 2 that seemed a bigger company but the sound is horrible so I figure it wasn't the right choice.

I suppose there's a better WAY to try most/all driver that were available in the setup without having to format the system sort of speak, deleting the VM then create a new one. Is there some kind of .ini file somewhat that I chould change an entry? Is there a table of the choice title to the entry name (IE: "SUPER sound card 16"=ssc16.sys) and where could I find it? The best would be to return to the specific part of the setup so there would be a nice interface, something like (invented out of my mind) Quote

setup.exe /SECTION audio /mode single
(single for single section).

Thank you KINDLY for your help
732.

Solve : Need Help with a replaceable parameter in a batch program?

Answer»

I've been at this for the last 3 hours and I finally got my replaceable parameter command to work.  The problem I am having is using it in a batch program.  I have a menu program that when you hit the specific menu number the batch program that was created would kick in.  Now if I run batch program on its own it worksk, The  problem is how do I get the replaceable parameter batch program I created to run.  when I hit the menu option it automatically runs it with errors.  I guess what I'm asking how can I get the batch program to issue the command and ask the user for the parameter 1 and parameter 2

When I run the program I get the following error message: The SYSTEM cannot FIND the path specified


here is my menu program batch file:


echo
REM Author Nick
echo off
f:
cd \menuprogram
CLS
echo.
REM Display Menu
echo.
echo **********************************************
echo ***     Nick's UTILITY Menu            ***
echo **********************************************
echo.
echo   1. Create a subdirectory named d:\computerrx
echo   2. Make inventory fiiles
echo   3. Copy Files
echo   4. Copy any file from any directory to d:\computerrx\backup
echo.   
echo.
echo off
pause


Here is the batch file I am having trouble with, this refers to menu option 4,

file name is 4.bat

echo off
REM Author Nick   
echo off
REM batch program that will ALLOW user to copy any file located in any directory
REM to any drive, any directory, and name any name
echo.
echo.
f:
cd menu program
pause
copy f:%1 f:\%2
echo.
echo.
rem loop back to menu
cd menuprogram
menu.bat

Any help would be so appreciated.  I am so new to MS DOS / Command line programing so any advice or guidence I would be so greatful.Please use Bulletin Board CODE tags around your CODE to distinguish code from general comments.  It really helps a lot.
http://en.wikipedia.org/wiki/BBCode

You are not showing us the entire code from the menu batch file so I have no idea how you are executing the 4.bat file from the Menu batch file.

If you are using Menu.bat to execute 4.bat it doesn't make any sense to then execute menu.bat from 4.bat

You need to show us all the code from each batch file.Hello Squashman, the menu.bat is the entire batch file for the menu program.

at the end of the 4.bat program i want the batch program to loop back to the menu that is why have it there.

I would like the user to hit option 4 on the menu and be given the replaceable parameter command along with request to enter the parameters.   What version of Windows will you be running this batch file on? Code: [Select]echo off
REM Author Nick

pushd F:\menuprogram

REM Display Menu
:menu
cls
echo.
echo **********************************************
echo ***     Nick's Utility Menu            ***
echo **********************************************
echo.
echo   1. Create a subdirectory named d:\computerrx
echo   2. Make inventory fiiles
echo   3. Copy Files
echo   4. Copy any file from any directory to d:\computerrx\backup
echo   5. exit
echo.   
set /p ans=Please select an option:
IF "%ans%"=="5" exit /b
IF "%ans%"=="4" goto copyfile
goto menu

:copyfile
REM Function that will allow user to copy any file located in any directory
REM to any drive, any directory, and name any name
:source
set /p source=Please type source path and file name:
IF NOT EXIST "F:\%source%" echo Source file does not exist &goto source
set /p dest=Please type destination path and file name:
copy "F:\%source%" "F:\%dest%"
goto Menu

733.

Solve : Batch only file name... from a?

Answer»

Hi,
please help
I ´ve 2 files:
in d:\Temp\Testing\
Docs20120101.csv
marti.rar

and i want a batch that rename the file marti.rar to Docs20120101.rar(like de csv file) it´s possible?
everday is a direrente file whit a diferente date()..
Thanks.Rename marti.rar Docs20120101.rarFor YYYYMMDD form.
Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~6%%date:~3,2%%date:~0,2%.rar

For YYYYDDMM form.
Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~6%%date:~0,2%%date:~3,2%.rar

Quote from: Sirim on January 06, 2012, 05:48:04 AM

For YYYYMMDD form.
Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~6%%date:~3,2%%date:~0,2%.rar

For YYYYDDMM form.
Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~6%%date:~0,2%%date:~3,2%.rar

Your offset is off by a few characters. For your first one it should be Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~10%%date:~4,2%%date:~7,2%.rarand your second should be Code: [Select]ren d:\Temp\Testing\marti.rar d:\Temp\Testing\Docs%date:~10%%date:~7,2%%date:~4,2%.rar
Unless your date variable expands differently than mine..

Code: [Select]c:\>echo %date%
Fri 01/06/2012

c:\> Quote from: Raven19528 on January 06, 2012, 10:27:27 AM

Unless your date variable expands differently than mine..


You mean like this?

Code: [Select]C:>echo %date%
06/01/2012 Quote from: Salmon Trout on January 06, 2012, 10:47:00 AM
You mean like this?

Code: [Select]C:>echo %date%
06/01/2012

Yep. Just like that. Maybe it would be better to explain the offset and parsing aspect of variables rather than try to assume how the OPs date variable expands. Unless the OP would like to show us how the date variable expands on his/her CPU.I made a mistake in my first answer, such that it would not work whatever the %date% EXPANSION. Ren does not expect a path when specifying the new file name. The code below is correct.

My %date% expands just like Salmon Trout's.

Something that would work on either of the expansions mentioned so far (ALTHOUGH not on any others):

On UK systems for YYYYMMDD or on US systems for YYYYDDMM.
Code: [Select]if "%date%"=="%date: =%" (ren d:\Temp\Testing\marti.rar Docs%date:~6%%date:~3,2%%date:~0,2%.rar) else ren d:\Temp\Testing\marti.rar Docs%date:~10%%date:~7,2%%date:~4,2%.rar
On UK systems for YYYYDDMM or on US systems for YYYYMMDD.
Code: [Select]if "%date%"=="%date: =%" (ren d:\Temp\Testing\marti.rar Docs%date:~6%%date:~0,2%%date:~3,2%.rar) else ren d:\Temp\Testing\marti.rar Docs%date:~10%%date:~4,2%%date:~7,2%.rar
I AGREE that it would be a lot easier if the OP showed their %date% expansion.Hybrid script works in any locale

Code: [Select]echo off
echo Wscript.echo eval(WScript.Arguments(0)) > evaluate.vbs
for /f "delims=" %%A in ( ' cscript //nologo evaluate.vbs "YEAR  (date)" ' ) do set yyyy=%%A
for /f "delims=" %%A in ( ' cscript //nologo evaluate.vbs "Month (date)" ' ) do set mm=%%A
for /f "delims=" %%A in ( ' cscript //nologo evaluate.vbs "Day   (date)" ' ) do set dd=%%A
del evaluate.vbs
if %mm% lss 10 set mm=0%mm%
if %dd% lss 10 set dd=0%dd%
echo yyyy       %yyyy%
echo mm         %mm%
echo dd         %dd%
echo yyyymmdd   %yyyy%%mm%%dd%
echo yyyy-mm-dd %yyyy%-%mm%-%dd%
echo mm/dd/yyyy %mm%/%dd%/%yyyy%

set examplevar=%yyyy%%mm%%dd%


Code: [Select]yyyy       2012
mm         01
dd         06
yyyymmdd   20120106
yyyy-mm-dd 2012-01-06
mm/dd/yyyy 01/06/2012
There is a lot of stuff here that I don't understand. I thought you just wanted to rename something. If so I would do it this way:

Create a batch file. We will call it 'rename.bat'

The file would look like this:

ren marti.rar Doc2012%1

I am not sure if I have the wording correct as I can't see your message, but you get the idea. When you run the file simply enter 'rename mmdd' where mmdd is the month and day. (or day and month if you wan this order.

Since there is a lot of other stuff POSTED in posts to your message I am not sure if this is what you want. If you already have a batchfile to run the other programs you can just include this in it and enter the mmdd info when you run that batch file.

Hope it helps
Jim, the O/P has not posted back in over a month so we will never know what solved their problem.
734.

Solve : Time Set Batch Files?

Answer»

Hello everyone,

I am a windows XP user actually, but in the time of dos games i had a dos computer so i know a little about the dos commands and whatnot. However what i want to ask today exceeds my knowledge. Let me explain it.

Well, i want to learn if i can write a batch file that will be processed at a specified time and date on dos 6.22. There is a dos software that i use and i want that software to realize some commands at a specified time without manual intervention. And basically those commands are given by pressing simple keys like letters and numbers. So i thought that running a batch file in the background can do the same. Is it possible to write such a batch file and put it into action?

Thanks in advance to everyone.batch files cannot simulate pressing keys on the keyboard.  I don't believe you can pull off the task scheduling either unless you have a batch file that sits there and runs by itself and keeps checking the time.
If you were running it on XP and had access to VBScript, you could easily test for a time condition and have it use the SENDKEYS FUNCTION to simulate pressing certain keys.

Would seeing the VBScript help you, or are you strictly looking to do this in batch?Thanks to everyone for replies and the PMs.

First i want to clarify that this operation needs to be done on a ms-dos 6.22 running computer. Not on a xp installed computer, but again ms-dos 6.22 installed computer. So, at command isn't recognized on ms-dos 6.22. Because when i write this;

C:\>at /?
Bad command or file name

C:\>

I get this.

Squashman, is it because when a line only contains the "y" caracter, what actually that does is to press y key and then the enter? Is this why it can't simulate?

Raven19528 Do you THINK a similar method can be applied on MS-DOS 6.22? Quote

Thanks to everyone for replies and the PMs.

If you don't mind me asking...who are these PM's from ? ? Quote from: patio on February 08, 2012, 04:05:10 PM
If you don't mind me asking...who are these PM's from ? ?
Yes, indeed.  Support is supposed to be limited to the forums or the chat service.  Support is NOT supposed to be provided in PM's.We all know who sends "support" via PMs.
Quote from: astaf on February 08, 2012, 03:18:34 AM
Raven19528 Do you think a similar method can be applied on MS-DOS 6.22?

I am not familiar with MS-DOS 6.22, but from what I do know about DOS, I doubt it. I have learned a great deal about cmd line batch filing, but I am by no means an expert in the DOS realm. At this point, I think it best that I let someone who knows a lot more about your specifics take a crack at it. Quote from: Salmon Trout on February 09, 2012, 11:09:57 AM
We all know who sends "support" via PMs.

I knew that and that's why i asked...That was a quick delete. Quote from: Raven19528 on February 09, 2012, 06:32:49 PM
That was a quick delete.

THANX...raven19528 I think it's not possible or requires much experience to do it, since i can't get a solution in this well-equipped forum.I am fairly sure that in MS-DOS 6.22, which is a single-tasking OS, you can't make one app press keys while another app is running.
That's reasonable considering that you say it is a single-tasking OS. Thanks.I do a LOT of processing in DOS. I write short EXE programs to do most anything I want. I use RPG. It is quick easy, and makes comact programs. Usually 25-100k. I also use quite a few batch files. If you want to do it at the same time every day, there is a dos comand 'waitfor xx:xx. If you want to do it on certain days, there is a command that checks the day of the week. It is 'datechek' It will return an errorlevel 0-6 for Sunday-Saturday. I think these commands work on all vesions of DOS

Hope this HELPS.
735.

Solve : Batch with Ascii Art and FTP Login... need help?

Answer»

Hi,

i would like to create a batch for ftp login... But i want also that i can enter a special dir-name and after login into this dir all files should be leeched...
sry 4 my bad english i'm out of practice for some years:)

So here is my script...

Code: [Select]echo off

echo    _____    ___________________
echo   /  _  \  /   _____/\______   \
echo  /  /_\  \ \_____  \  |     ___/
echo /    |    \/        \ |    |
echo \____|__  /_______  / |____|
echo  arCi's \/  SiTE  \/  PROJECT
echo
echo   PRiVAT & SECURE SiNCE 2K8
echo.
echo Please input a Scene-Release:
set /p rel=
echo.
echo Release was set on ASP
echo.
echo Ready for Connection? (Y/N)
set /p answer=
if %answer% == Y goto con
if %answer% == N goto end
:end
exit
:con
clear
echo    _____    ___________________
echo   /  _  \  /   _____/\______   \
echo  /  /_\  \ \_____  \  |     ___/
echo /    |    \/        \ |    |
echo \____|__  /_______  / |____|
echo  arCi's \/  SiTE  \/  PROJECT
echo.
echo   PRiVAT & SECURE SiNCE 2K8
echo.
echo.
echo  establish Connection...
echo.
ftp xxx.xxx.xxx.xxx xxxxx
USER
USERPW
cd incoming/%rel%
REM mget -r * (mit a besteatigen)

I think the Problem was the ascii art... can MAYBE use the echo command like this... echo "ascii here..." ?

hope anyone got some HINTS for me

thx arCiYou need to put your FTP commands into a SCRIPT file and then execute the FTP command with the script file you created.
http://technet.microsoft.com/en-us/library/bb490910.aspxok but what's with the "set /p rel=" part? If i got this in the first script does it work also for the "ftp-script"?
And whats with the "echo-error"?

that's confusing me:)This is what the end of your batch file should look like.
Code: [Select](Echo.open ftp.somedomain.com
Echo.user username
Echo.password
Echo.cd incoming/%rel%
echo.mget -r *
Echo.quit
)>ftpscript.scr

ftp.exe -n -i -s:ftpscript.scrok i've put the ftp stuff into another file and got just the last line in my first file...

ftp.exe -n -i -s:asp.ftp

I think that should be work... I'll check it now


//EDIT

if i run asp.bat i get this error....
Code: [Select]D:\>asp
   _____    ___________________
  /  _  \  /   _____/\______   \
Der Befehl "___" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.
Still Problem with the ascii-art... How can i fix this? Quote from: arcanus on February 13, 2012, 11:48:28 AM

if i run asp.bat i get this error....
Code: [Select]D:\>asp
   _____    ___________________
  /  _  \  /   _____/\______   \
Der Befehl "___" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.
Still Problem with the ascii-art... How can i fix this?

Your third ASCII art line has this character |

This is the pipe symbol.

Echo blablabla | lalala

means pipe text blablabla to program lalala

So the ascii art after the pipe symbol is triggering the error. Because there is no program named "___".

Escape the pipe symbols with a caret so | becomes ^|

Also escape < and > if you use them.





Quote from: arcanus on February 13, 2012, 11:48:28 AM
ok i've put the ftp stuff into another file and got just the last line in my first file...

ftp.exe -n -i -s:asp.ftp

I think that should be work... I'll check it now
But that forces you to hard code the directory you need to change to.  You cannot ask for it in your batch file now.Ok now it works... the asp.bat works well but i set on this file a path with:

set /p rel=

And in the ftp file i want go to this dir with

cd blabla/%rel%

this doesn't work... how can i make this working?


greetz arCi Quote from: arcanus on February 14, 2012, 09:09:55 AM
Ok now it works... the asp.bat works well but i set on this file a path with:

set /p rel=

And in the ftp file i want go to this dir with

cd blabla/%rel%

this doesn't work... how can i make this working?


greetz arCi
I gave you the code in my 2nd post and then told you about your issue in my 3rd post.  You need to create the FTP script on the fly with the code I gave you.i know and i make 2 files...

1 File with the asciiart in (asp.bat)

1 File with the ftp Stuff (asp.ftp)

the ftp file looks like this now:

Code: [Select]open xxx.xxx.xx.xx xxxxx
user username
password
cd incoming/%rel%
mget -r *
quit
i removed the echo. commands because it won't work with that.


Here is the asp.bat file:

Code: [Select]echo off

echo    _____    ___________________
echo   /  _  \  /   _____/\______   \
echo  /  /_\  \ \_____  \ ^|     ___/
echo /   ^|    \/        \^|   ^|
echo \___^|__  /_______  /^|___^|
echo  arCi's \/  SiTE  \/  PROJECT
echo.
echo   PRiVAT + SECURE SiNCE 2K8
echo.
echo Please input a Scene-Release:
set /p rel=
echo.
echo Release was set on ASP
echo.
echo Ready for Connection? (Y/N)
set /p answer=
if %answer% == Y goto con
if %answer% == N goto end
:end
exit
:con
clear
echo    _____    ___________________
echo   /  _  \  /   _____/\______   \
echo  /  /_\  \ \_____  \ ^|     ___/
echo /   ^|    \/        \^|   ^|
echo \___^|__  /_______  /^|___^|
echo  arCi's \/  SiTE  \/  PROJECT
echo.
echo   PRiVAT + SECURE SiNCE 2K8
echo.
echo.
echo  establish Connection...
echo.
ftp.exe -n -i -s:asp.ftp
btw thx 4 your help and time u spend here... For the third time I told you that the FTP script needs to be created on the FLY by the BATCH File.  I told you in my 2nd post: "This is what the end of your batch file needs to look like!"  You need to use the code I gave you to create the ftp script with the batch file.  You cannot have the FTP script already created!sorry i told u my english sucks... But now i've understand it... with your code the ftp file will created when i START the bat...

test... and it works fine.

So but now i've got the *.bat file with the user and pw inside... Is there a way to encrypt it?
That no1 can read what's inside... Quote from: arcanus on February 14, 2012, 11:59:13 AM
sorry i told u my english sucks... But now i've understand it... with your code the ftp file will created when i start the bat...

test... and it works fine.

So but now i've got the *.bat file with the user and pw inside... Is there a way to encrypt it?
That no1 can read what's inside...
There are programs that will take your BATCH file and wrap it into an executable. But there are plenty of issues with that.  All they are really doing is creating a self extracting executable file that launches the batch file.  Many of these programs extract the batch file to a temporary folder which then becomes the working directory.  If you are trying to DOWNLOAD files to the directory that the executable is launched from it will end up downloading them to the temporary folder that batch file was executed from.

You could always just prompt for the username and password in the batch file and echo those variables to your script.Yes i try bat2exe or bat2com but the created exe or com-file doesn't work well...
Maybe it's rly the best to make a prompt for user/pass...

Ok thx 4 all Squashman Whoooshe...
736.

Solve : Some advanced techniques and efficiencies?

Answer»

Hey all,

Usually I'm answering others but was wondering if I could get a little help on something I've been working on. I've got a batch file that displays two columns of information, and it's fairly easy to get that to work with spacing and everything. What I'm wanting to do is make it so that I don't chop words at all, like most word PROCESSORS. Obviously there is no set size for the data or this would be a simple task, and I know what I need to do and how to do it, but was more looking for if there was a way to make it more efficient. Here is what I have, the VARIABLES are fairly self explanatory I hope:

Code: [Select]:setdisplay
set taskline1=Description: %taskdesc:~0,16%
set goalline1=Description: %goaldesc:~0,16%
set taskcut=29
set goalcut=29
:task1loop
call set taskcheck=%%taskline1:~!taskcut!,1%%
if "taskcheck"==" " (goto task2loop)
set /a taskcut-=1
goto task1loop
...

So this goes on and basically sets 6 lines of text for these descriptions without cutting words appart (spacing is taken care of seperately). What I am wanting is to know if there is a way that I can make this more efficient? I've been racking my brain on it now for a while so I'm hoping another set of eyes will help to get past the mental block I'm having.

Thanks.Have you considered hyphenation?
Hyphens | Punctuation Rules




That would work, except when there is a space at the end of the line, then it would just look goofy. Since I would have to go through the testing phase for that, I might as well make it look as good as possible.Hi Raven,
I am really visual person. I kind of need to see what your input looks like and what you expect the output to look like.Essentially there are going to be two columns displayed on the page that have info from a data file. The description is the only one that I'm worried about as it is likely to be the only thing that requires multiple lines. In the end, I would like the display to look something like this:

Code: [Select]Task ID: 4                   /Goal ID: 1
Description: Grab serial      /Description: Create the
numbers of the printers in   /Reports part of this program
The front office and do the  /to include reports of tasks
paperwork to get rid of them./active, completed, etc.
                             /
Notice that there are no broken words (as there would be the way the program was set ORIGINALLY.) This is what the program is going to end up doing, I'm just looking for a more efficient way of doing it.Alright, so have been trying to be as efficient as possible on this one, and have hit a non-working roadblock. Trying to use the for /l to assign multiple lines in as few lines of code as possible. I've looked it over again and again, and I don't see what is going wrong. I think it has to do with when the variables are being expanded, but when ran, I get multiple "The syntax of the command is incorrect." Anybody know what the deal is?

Code: [Select]for /f "usebackq" %%a in (`linecut.bat 0 16 "%taskdes%"`) do (set length=%%a)
call set taskline1=Description: %taskdes:~0,^%length%%
set offset=%length%
for /l %%b in (2,1,6) do (
  set length=29
  for /f "usebackq" %%F in (`linecut.bat !offset! !length! "%taskdes%"`) do (set length=%%F)
  call set taskline%%b=%taskdes:~^!offset!,^!length!%
  set /a offset=!offset!+!length!
)
%taskdes% is set earlier in the script and is a description of the task. Below is the linecut.bat file that is being UTILIZED:
Code: [Select]echo off

set offset=%1
set length=%2
set textline=%3
echo %offset% | findstr /i [a-z]
if errorlevel 1 (goto loop) else (
  set length=0
  goto end
)
echo %length% | findstr /i [a-z]
if errorlevel 1 (goto loop) else (
  set length=0
  goto end
)
:loop
call set textcut=%%textline:~^%offset%,%length%%%
if not "%textcut:~-1,1%"=="" (
  if not "%textcut:~-1,1%"==" " (
    set /a length-=1
    goto loop
  )
)
set /a length-=1
:end
echo %length%
exit
I'm stumped. So any help would be great. Thanks.

737.

Solve : need a little script or software program to remove the .vir extensions on files?

Answer»

can anyone please help me with this:  I have a folder that has FILES and subfolders  and all the files have the .VIR extension APPENDED  by an antivirus program.  I know these are not infected, I just want to RECOVER them back to the original file extension.  example -- dimstat.pdf.vir should be dimstat.pdf   These files are part of a lighting design software and now the program doesn't work.  The subfolders can GO down 3 or 4 levels.  this is on a windows XP professional pc, SP3.Code: [Select]pushd "C:\path to top level folder\"
FOR /F "tokens=* delims=" %%G in ('dir /a-d /b /s *.vir') do rename "%%~G" "%%~dpnG"

738.

Solve : Batch file error level?

Answer»

I should be able to work this out myself, but my mind is not working quite right. I have a batch file. I have a command that returns an errorlevel form 0-6. One for each day of the week. I want to 'goto' a tag if the returned error level is 5 or 2. What is an EASYIf "%errorlevel%"=="5" goto foo
If "%errorlevel%"=="2" goto foobarThanks. Quick answer, good answer. I was not thinking in that manner..Errorlevel is a unique one that should allow for a few less special CHARACTERS

Code: [Select]if errorlevel 5 goto foo
if errorlevel 2 goto foobar
Not a massive difference in anything, just a little quirk about batch. Quote from: Raven19528 on February 14, 2012, 03:43:40 PM

Not a massive difference in anything, just a little quirk about batch.

The old MS-DOS if errorlevel command syntax was preserved in modern Windows command language for backwards compatibilty. In the old version, "if errorlevel N do something" means "if the errorlevel is N or more do something", which is why you have to test for the errorlevels you are interested in, in DESCENDING order. However, the modern version where you test a regular variable called %errorlevel% does not have this restriction, and if you use the arithmetc comparison operators (instead of QUOTES and double equals sign):

EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal

you don't need any quotes either

if %errorlevel% equ 0
if %errorlevel% neq 0
if %errorlevel% gtr  0

etc

so you can do without gotos and LABELS too

if %errorlevel% equ 5 (
    rem the stuff at the :foo LABEL
    command1
    command2
    etc
    )

if %errorlevel% equ 2 (
    rem the stuff at the :foobar label
    command3
    command4
    etc
    )

739.

Solve : Batch help.?

Answer»

Hello,

I have known simple batch stuff for a while. And only just started to get back into it.


Hopefully someone out their can answer my questions:)


Basically i have uploaded a FOLDER(BOB-FOLDER) which users download. The users save the folder(BOB-FOLDER) to their desktop, The folder contains .dll files and files that already exists.
The batch file searches for this folder on their desktop and then it searches for the folder where the BOB-FOLDER is to be copied to. If the batch searches and cant find either folder it closes the batch. Theirs no prolem here.

What i am after is how can i copy the files in BOB-FOLDER on desktop(%USERPROFILE%\Desktop\BOB-FOLDER\files) to C:\PROGRA~1\BOBTEST~1\TEST
Also if the file exists which it already will because this UPDATES the .dll files, It probrally wont work. So how can i make it copy the folders files and to make sure UAC and Parental Controls allow this feature.

Im thinking i would need to add a message box thats asks for their permission to move and replace files. I dont mind if the batch does that.

But how do i go about doing this process?I hope I'm understanding your question correctly.

In order to copy all the folders from BOB-FOLDER\files to C:\PROGRA~1\BOBTEST~1\TEST, you would use:
Code: [Select]copy %USERPROFILE%\Desktop\BOB-FOLDER\files\*.* C:\PROGRA~1\BOBTEST~1\TESTThat should work.

About the message box... there would be a complicated VBScript WAY to do that, but a simpler way to ask for confirmation is:
Code: [Select]set /p x=Are you sure you want to copy BOB-FOLDER's files? [Y/N]:
if /I '%x%' == 'y' (
goto copybob
) else (
echo No? Okay, press any key to close...
pause > nul
exit
)

:copybob
copy %USERPROFILE%\Desktop\BOB-FOLDER\files\*.* C:\PROGRA~1\BOBTEST~1\TEST && echo Copy successful.
pause

When prompted, press Y to copy the files and any other key to not do it.

This file assumes that BOB-FOLDER\files exists... if you need it to check, then use at the beginning:
Code: [Select]if not exist "%USERPROFILE%\Desktop\BOB-FOLDER\files\" echo Error! BOB does not exist &pause &exit

If you get any errors, tell me, I didn't test this.Ahhh beautiful.

I was using: MOVE %USERPROFILE%\Desktop\BOB-FOLDER\files*.* C:\PROGRA~1\BOBTEST~1\TEST
instead of  : MOVE %USERPROFILE%\Desktop\BOB-FOLDER\files\*.* C:\PROGRA~1\BOBTEST~1\TEST

Forgot the "\" ha.

Thankyou. Would this process still work the the person had User Account Control on and Parental Controls on?sorry to double post.

But if you once did that and this process still worked even if the person had User Account Control on and Parental Controls on; How would you delete a folder?

I know that DEL does this. But this doesnt work for all WINDOWS OS's How would i got about making a bathc that deletes a folder that will work on any windows OS eg it would delete a folder on winxp,win7,win8,vista? Quote from: bobbybronkxs on February 11, 2012, 06:47:29 PM

I know that DEL does this. But this doesnt work for all windows OS's How would i got about making a bathc that deletes a folder that will work on any windows OS eg it would delete a folder on winxp,win7,win8,vista?

I'm not sure if I'm understanding correctly, but if you want to delete a folder, try using the RMDIR command. That should work on Windows 2000 or up.
I don't know about windows 8, but it hasn't been officially released yet.
740.

Solve : Batch Programming Help - Renaming Files?

Answer»

So, I'm new to writing Batch files. I've got the basic algorithm, however it is the formatting and language I'm having problems with.

I'm trying to write a file that replace that will, for each and every text file found in "C:\files\" folder, SWITCH it's file name with it's content.

E.g. "file1.txt", "file2.txt", "file3.txt", and "file4.txt" exist in "C:\files\" folder. In "file1.txt" there is a line of text containing the single word "alpha". The other text files have DIFFERENT words as content.
       "file1.txt" containing the word "alpha" becomes "alpha.txt" containing the word "file1".

-------------------------------------------------------------------------------------------------------------------
Here's my go at it:


FOR /R %%F IN (*.txt) DO (
SET /p var= RENAME %%F %var%
%%F > (*.txt)
)

-------------------------------------------------------------------------------------------------------------------


It's not working and for the LOVE of all that is holy, I can't get my head around it.


NOW...if I can get it to switch file names back AND forth using the same batch file......

I would be so gracious as to even GIVE you an internet hug...., their not cheap y'know..?
I swear to god I just saw this same question on another forum the other day.

A yes here it was.  It is even you.
http://www.dostips.com/forum/viewtopic.php?f=3&t=2937What's the purpose of your post - it's obviously been answered elsewhere?Yeh, the guys at DOStips were really helpful. I had posted this on multiple forums trying to get some help. I've got the file working though and this thread is closed.

Thanks guys.

741.

Solve : MS-DOS application Date/Year format problem?

Answer»

Hello all of you!
I have problem with MS-Dos application date/year format. Aplication used for concrete production with databases of production, reports etc.
Everything work fine exept date/year format on reports and main SCREEN. In control settings of application date is 13/02/2012 and in main screen and reports show 13/02/112 (three digits). TRY change in BIOS,regional settings but nothing. ALSO try GOOGLE... I dont have source code... Can you help me?? Thanks!!!!!!!!!!!!!Possibly program is not year 2000 compliant.
Quote from: Salmon Trout on February 14, 2012, 06:26:35 AM

Possibly program is not year 2000 compliant.
Any solution without source code??1. Easy: Remember that "112" means "2012" and "113" means "2013" etc
2. Difficult: FIND software vendor and request updated version.
Quote from: Salmon Trout on February 14, 2012, 11:43:46 AM
1. Easy: Remember that "112" means "2012" and "113" means "2013" etc
2. Difficult: Find software vendor and request updated version.
I have problems with customers... Is any solution with some decompilers or something else... Just to try?? Thanks!!!!!!!!!!!!!Why didn't you give the name and version number of the program?
742.

Solve : How to break out of 'for /f ...' loop after one iteration?

Answer»

I am pretty new to batch writing and so the issue I have is probably more a problem of wrong approach rather than a fix for the path I am on.

I need to copy the 'latest' files from many sub directories up to their parent dirs.
The structures look like:

SourceFiles/Cust1/Archive/files.txt
SourceFiles/Cust2/Archive/files.txt
etc.

The Archive folders are filled with lots of files, I occationally need to MOVE the latest archived file back 'up' one dir to the CUST# folder for re-processing.
I have one for loop that marches through the Cust folders (using a temp dirlist.txt) building a temp filelist.txt (sorted by mod date latest first)and an INNER loop that reads in the filelist and copies the files to the destination. My problem is that I don't know how to gracefully exit the inner loop after 1 iteration. I tried using a GOTO to get back to the outer for loop, but that seemed to break the outer loop and cause it to exit after only 1 iteration as well.

In it's current form this batch will bring up ALL the files from the archive and that is bad for me!
***************************
set prodSourceFolderPath="C:\temp\SourceFiles1"
set qaSourceFolderPath="C:\temp\SourceFiles2"

DIR %prodSourceFolderPath% /A:D /B /O:N >  C:\temp\dirlist.txt
setlocal enabledelayedexpansion
 FOR /F %%d IN (C:\temp\dirlist.txt) DO (
   DIR %prodSourceFolderPath%\%%d\Archive /w /B /o:-d >  C:\temp\filelist.txt
   FOR /F "delims=" %%a IN (C:\temp\filelist.txt) DO (
      echo %%a
      set latestFile=%%a
      C:\WINDOWS\System32\xcopy.exe /q /r /y /i %prodSourceFolderPath%\%%d\Archive\!latestFile! %qaSourceFolderPath%\%%d
   )
)I was able to solve this on my own but I decided that I would have to move the inner loop logic out to a 2nd .BAT file. That allowed me to use GOTO w/out disturbing the outer loop:


1st batch file:
*************
DIR %prodSourceFolderPath% /A:D /B /O:N >  C:\temp\dirlist.txt
setlocal enabledelayedexpansion
 FOR /F %%d IN (C:\temp\dirlist.txt) DO (
   DIR %prodSourceFolderPath%\%%d\Archive /w /B /o:-d >  C:\temp\filelist.txt
   CALL T:\2nd.bat C:\temp\filelist.txt %prodSourceFolderPath%\%%d\Archive %qaSourceFolderPath%\%%d\
)

2nd  batch file:
*************

echo off
if %1'==' echo which file? && goto :eof

set DONE==N
for /f "tokens=*" %%L in (%1) do call :1 %%L %2 %3
goto :eof

:1
if %DONE%==Y goto :eof
echo %1
echo %3
C:\WINDOWS\System32\xcopy.exe /q /r /y /i %2\%1 %3
set DONE=Y
goto :eof

:eof
:: DONEWhat o/s were you using?   I tried this on Windows Server 2003 and it does not work.  I've also tried BREAK and EXIT /B, but it ALWAYS coninues to read the rest of the file.

Thanks for any other tips.You're responding to a post that is two years old. You'll get better attention if you start a new thread.

743.

Solve : Compare two folders and ontents.?

Answer»

I have TWO folders on efferent volumes, (Drives).
I am almost sure they are equal. But I need to be absolutely sure.
So the question is, How nan I be really sure that everything in one folder is also found in another folder, even sub directories and files?

I tried the FC command, but COULD not not get it to work. It says it can not file then file I specified.
You are not being clear on what your intended task is.

Are you wanting to compare files to see what their differences are?
Or, do you want to see if two directory structures have the exact same files and folders in it? Quote from: Squashman on February 14, 2012, 08:22:21 PM

You are not being clear on what your intended task is.

Are you wanting to compare files to see what their differences are?
Or, do you want to see if two directory structures have the exact same files and folders in it?
The LATER. I need to know if the two folders and sub-folders a re equal. The contents of both are from a download and I don't have nth check sum information. So I want to compare then two to see if they are equal.If the two directory structures are the same and only the Drive LETTERS are different (C:Source & F:\Source) then you could do this to see if the files exist in each.
Code: [Select]pushd C:\source
FOR /F "tokens=1,2 delims=:" %%G in ('dir /b /s') do (
     IF EXIST "F:%%H" echo file or folder exists in both drives
)WinDiff
744.

Solve : String Manipulation Batch?

Answer»

I am making a batch file where the user needs to drag a file into the command window. Both the filename and the path need to be stored in two separate variables (when the file is dragged into the window, the full path and filename is retrieved and stored in one variable). I found soooo many examples of this on google EXCEPT they all assumed that you would be using %1 and for me it's %arpath%. I can't figure out how to make the thing work with a variable instead of %1.

I looked here: http://arstechnica.com/civis/viewtopic.php?f=15&t=707278 and it said use %~nx1, BUT that only works with 1.

I have tried:
set filename=%~nx:arpath%
set filename=%~nx$arpath%
set filename=%~nxarpath%
set filename=%~nx:arpath
set filename=%arpath~nx%
set filename=%arpath:~nx%

Any ideas?That is how it works. You can't use the modifiers with a variable name you define. It only works with the command line arguments and the for loop variables.So the answer is there is no answer  for %%A in (%arpath%) do set filename=%%~nxA
That's brilliant. THANKS.  So how are you capturing the file you drag and drop into your variable?Figured it out.  Didn't realize you could use SET /P like that.Here it is incase you're interested. I had to zip it up because it requires some additional files. It is a utility to build installation programs using batch as the script and 7-zip as the archive.

Incase you don't want to open the zip, here is the code (doesn't work without other files):

Code: [Select]echo off
color 0a
echo 7-ZIP SFX Maker
echo ===============
echo File called install.bat or uninstall.bat in archive will be executed.
echo.
set /p unorin=Do you want to make an installer or uninstaller(i/u)?
set /p arpath=Drag source archive into this window and press enter:
for %%A in (%arpath%) do set thepath=%%~dpA
if %unorin%==i (
copy /b 7zsd.sfx + config.txt + %arpath% %thepath%install.exe
) else (
copy /b 7zsd.sfx + config2.txt + %arpath% %thepath%uninstall.exe
)

[YEAR+ old attachment deleted by admin] Quote from: Linux711 on February 21, 2012, 03:39:07 PM

So the answer is there is no answer 

You waited under 9 minutes before making this petulant bump. This is not really acceptable. I wish now that I had waited 12 hours to tell you about FOR. Quote
This is not really acceptable. I wish now that I had waited 12 hours to tell you about FOR.

I apologize. I waited so little time after that first response because the way he said it, it sounded like there was no solution and I thought if I left it that way everyone would just read his post and think "up. not possible. moving on."

But you didn't wait until 12 hours, so either you answered it anyway (in which case I appreciate it) or you just found out that it had been 9 minutes now.My bad anyways.  The Majority of my batch files that we use here at work are drag and drop.  The ones that are drag and drop the user drags and drops all the files they need to process onto the batch file.  Everyone in my department knows that is how they work.  So if you really wanted to do it that way you could just inform your users that all they need to do is drag a file or folder on top of the batch file and that will launch the batch file as well.  Otherwise your users are doing 3 steps just to get the file path into the batch file.
1) They double click to launch the batch file
2) They drag and drop the file into the cmd window
3) They then need to hit enter for the SET /P to take the input.

If you just have your batch file accept the %1 as the input all they have to do is
1) drag the file onto the batch file

What I usually do at the top of all my scripts is check to see if %1 is not defined.  If it isn't I GOTO a label at the bottom of my script called USAGE.  It explains to the user that they MUST drag and drop the files they want to process onto the batch file.

You could in theory have your batch file setup both ways.  You could do an IF statement after your first QUESTION to see if %1 is defined and if it is SET it to your Path variable and GOTO a label after after your FOR LOOP. Quote from: Squashman on February 22, 2012, 05:11:05 AM
What I usually do at the top of all my scripts is check to see if %1 is not defined.

Is the coding for this simply if defined %1? I'm having some issues with a called script and I'm trying to break it down to it's basic parts and troubleshoot individually, but still running into snags. Also, when a script is called from cmd line or batch, does it see something in QUOTES as one variable to be passed? I.e. program.exe 2 3 "Hello all" would pass three variables to the program, not 4? I'm pretty sure this is the case, but looking to verify it before troubleshooting further. Quote from: Raven19528 on February 22, 2012, 12:44:48 PM
Is the coding for this simply if defined %1?

if [not] defined only works with regular %var% type variables (those which normally have a percent sign before and after) not the single-percent sign-and-number replaceable parameters, so you'd have to do this

(notice there aren't any percent signs surrounding the variable name after the defined keyword)

Code: [Select]set var=%1
if defined var echo YES
if not defined var echo NO

Code: [Select]set var=%1
if defined var (
    echo YES
) else (
   echo NO
)

Or you can work directly with %1 to %9

Code: [Select]if not "%1"=="" echo YES
if "%1"=="" echo NO

Code: [Select]if not "%1"=="" (
    echo YES
) else (
    echo NO
)

Moving on...

Quote
program.exe 2 3 "Hello all" would pass three variables to the program, not 4?

test.bat

Code: [Select]echo off
echo parameter 1 is [%1] parameter 2 is [%2] parameter 3 is [%3] parameter 4 is [%4]
test.bat 2 3 "Hello all"

See the result...





I shouldn't have said defined. I just do a comparison with an IF statement.
IF "%1"=="" goto usage
745.

Solve : How to remove folder in Local Settings\Application data from a BAT file??

Answer»

I use BAT files to manage and/or delete cache FOLDER(s) on computers which I use.

Example:

To remove folder "Test" from the following full path on my HARD drive:

   C:\Documents and Settings\>\Application Data\Test

I would use the BAT file syntax as follows:

   rd "%appdata%\Test\" /s /q




But, what syntax I could use to remove folder Test if it is locatet at the following location on my hard drive:

   C:\Documents and Settings\>\LOCAL SETTINGS\application data\test ?

Does anyone know the coorrect syntax for this (for BAT files for WinXP)

Thanks in ADVANCE for your suggestions
 

__________________
Edit: Just found it; the syntax would be:

   rd "%UserProfile%\Local Settings\Application Data\Test\"  /s /q


Sorry for this trouble!
BEST REGARDS!
If you know what the path is why aren't you just hard coding the path?The full path is different depending on the user name on different computers
But you also have 2 other Environmental variables you can use that have the users name in it.

746.

Solve : Batch file to change to a specific date?

Answer»

I need to write a batch file so I can set the date to start a program, but I then need to change back to the current date after the program has loaded. I've not written any batch files in a long time and can't work out how to do it.This is dependent on your regional and language settings.
My date format is set to only output a 2 digit year yours is probably a 4 digit year.
Code: [Select]H:\>echo %date%
Wed 01/11/12
So for a two digit year you could do this.
Code: [Select]SET TODAY=%date:~4,2%-%date:~7,2%-%date:~10,2%
REM setting date back to an older date
DATE 12-11-11
start "" "C:\path to my program\myprogram.exe"
REM Changing date back to todays date
DATE %TODAY%If you have a 4 digit year change the last DATE string to %date:~10,4% Quote from: The Artilleryman on JANUARY 11, 2012, 05:04:44 AM

I need to write a batch file so I can set the date to start a program,

Why? Has the trial period EXPIRED?
It's a parts catalogue, new one issued every month, no longer got access to latest one so having to use an old one. Quote from: Squashman on January 11, 2012, 07:53:01 AM
This is dependent on your regional and language settings.
My date format is set to only output a 2 digit year yours is probably a 4 digit year.
Code: [Select]H:\>echo %date%
Wed 01/11/12
So for a two digit year you could do this.
Code: [Select]SET TODAY=%date:~4,2%-%date:~7,2%-%date:~10,2%
REM setting date back to an older date
DATE 12-11-11
start "" "C:\path to my program\myprogram.exe"
REM Changing date back to todays date
DATE %TODAY%If you have a 4 digit year change the last DATE string to %date:~10,4%



I'm using XP and the date format is wrong, I get   today=1/-01- You need to show me how the date variable outputs from the cmd prompt just like I showed you in my first post.It looks like it is likely UK date output, which expands DD/MM/YYYY.

Let's modify for that and see if it works out better for the OP. Quote from: Raven19528 on January 11, 2012, 11:47:40 AM
It looks like it is likely UK date output

I think I once saw the Artilleryman at Horsell Common, near Woking.
Quote from: Squashman on January 11, 2012, 10:39:46 AM
You need to show me how the date variable outputs from the cmd prompt just like I showed you in my first post.

OK I've worked out the first line for saving today's date

SET TODAY=%date:~0,2%-%date:~3,2%-%date:~6,4%
this gives me  12-01-2012

I'm using
C:\myprog\myprog.exe

which starts the prog OK, but after loading the prog the batch file stops and only completes after exiting the prog, what I realy need to do is reset the date once the prog has loaded.
 Line 3   start "" "C:\myprog\myprog.exe"   IGNORES the date change.Here is an excerpt from the start /? text that I think specifies the problem:

Code: [Select]Microsoft Windows [Version 6.1.7601]
When executing an application that is a 32-bit GUI application, CMD.EXE
    does not wait for the application to terminate before returning to
    the command prompt.  This new behavior does NOT occur if executing
    within a command script.

The way around this is to "start" a different command process, which in turn starts the program, but never takes control away from your original batch file. Example:

Code: [Select]SET TODAY=%date:~0,2%-%date:~3,2%-%date:~6,4%
REM setting date back to an older date
DATE 12-11-11
(echo start "" "C:\path to my program\myprogram.exe"
echo del ^%^0) >tempstart.bat
start "" tempstart.bat
REM Changing date back to todays date
ping 1.1.1.1 -n 1 -w 2000>nul
DATE %TODAY%

This may or may not be a long enough delay (2 seconds), but it does institute a slight delay before changing the date back to today. If this isn't required, you can remove the ping line. Quote from: The Artilleryman on January 12, 2012, 10:17:27 AM
which starts the prog OK, but after loading the prog the batch file stops and only completes after exiting the prog, what I realy need to do is reset the date once the prog has loaded.
 Line 3   start "" "C:\myprog\myprog.exe"   ignores the date change.
I don't throw out random code for my good health. I gave you the correct code for starting the program in my first post. I had no control over the date output as I explained in both of my previous posts because anyone can change the short date format in their regional settings.Hi all

This is my elegant solution to solving the date issue

Edit launch to read the Progam
Just amend the dates 01/01/2012 to whatever date you require
Amend c:\...... to the shortcut properties of the program you wish to run
When you exit the program the date will rest to today!

Just copy and paste into notepad and SAVE as a .bat file

ECHO OFF
CLS
:MENU
ECHO.
ECHO ....................................... ........
ECHO PRESS 1 to select your task, or 2 to EXIT.
ECHO ....................................... ........
ECHO.
ECHO 1 - Launch xxxxxxxxxxxx
ECHO 2 - Exit
ECHO.
SET /P M=Type 1, 2, then press ENTER:
IF %M%==1 GOTO PROGRAM
IF %M%==2 GOTO RESETDATE

:PROGRAM
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CURDATE=%DATE%
COLOR 4f
echo Setting System date to 01/01/2012
echo.
date 01/01/2012
echo Launching Program........Please Wait
echo.
"c:\xxxxxxxxx.exe"
echo Resetting System Date back to Todays Date....Please Wait
date %CURDATE%



Hope this helps

Jules Code: [Select]SET /P M=Type 1, 2, then press ENTER:
What will happen if the user TYPES 3 or just presses ENTER?

None of the scripts in this thread should be run sufficiently close to midnight that the line with the start command finishes the next day.


Nothing!  You could delete the first section and just run the program batch file but remember running a date change could corrupt other files you save and will certainly impact your internet browser home page  so be careful  - hence to 1 or 2 check to make sure.

Julian

Quote from: jjh281 on February 29, 2012, 01:50:00 PM
Nothing!

If the user types 3 and presses Enter, neither of the following IF tests will be satisfied, so the script will fall through to :PROGRAM, and if they just press ENTER, then %M% will be set to an empty string, and the script will halt with an error at the first IF test.


747.

Solve : get the sum of %errorlevel% at the end of a subroutine.?

Answer»

I composed a batch file to ping a list of DEVICES, and return a notification whenever a device did not reply. These errors are also prepend to an existing logfile.

All this works fine, here is my current script: (I don't think I have to explain the steps to you guru's...)

Code: [Select]echo off
set fnm=D:\scripts\testip.txt
set tnm=D:\scripts\testtemp.txt
set lnm=D:\scripts\testpingme.txt

if exist %fnm% goto :Label1

echo.
echo Cannot find %fnm%
echo.
pause
goto :eof

:Label1
Set _t1=google.com ::Here I set my domain name to check if I am in the correct domain
ping %_t1% -n 1
if %ERRORLEVEL% EQU 1 goto :Label2
echo YOU ARE CONNECTED
goto :Label3

:Label2
echo    ***************************************************** >> %tnm%
echo    ***************************************************** >> %tnm%
echo    ** PingTest CANCELLED on %date% at %time% ** >> %tnm%
echo    ** Reason: YOU ARE NOT CONNECTED TO THE OFFICE NETWORK ** >> %tnm%
echo    ***************************************************** >> %tnm%
echo    ***************************************************** >> %tnm%
echo * >> %tnm%
type "testpingme.txt" >> "testtemp.txt"
del "testpingme.txt"
ren "testtemp.txt" "testpingme.txt"
MSG "%username%" /TIME:5 Pingtest CANCELLED
goto :eof

:Label3
echo    ***************************************************** >> %tnm%
echo    ***************************************************** >> %tnm%
echo    ** PingTest STARTED on %date% at %time%   ** >> %tnm%
echo    **                                                 ** >> %tnm%
echo.
for /f "skip=1 tokens=1,2 eol=;" %%a in (%fnm%) do call :sub %%a %%B
echo.
echo    **                                                 ** >> %tnm%
echo    ** PingTest ENDED on %date% at %time%     ** >> %tnm%
echo    ***************************************************** >> %tnm%
echo    ***************************************************** >> %tnm%
echo * >> %tnm%
type "testpingme.txt" >> "testtemp.txt"
del "testpingme.txt"
ren "testtemp.txt" "testpingme.txt"
goto :eof

:Sub
ping -n 1 %1
IF %ERRORLEVEL% EQU 1 ECHO    **  # %1 - %2 is not responding     ** >> %tnm%
IF %ERRORLEVEL% EQU 1 (mplayerc.exe /minimized /play /close "dingdong.wav") & MSG "%username%" /TIME:600 %2 - %1 is not responding

Now what I'm trying to do next is, I want to have a message box (only when errors have occurred)asking if I want to see the logfile.

to GET this messagebox i could find a vbs script doing that
Code: [Select]Option Explicit
Dim oShell, retCode
Set oShell = WScript.CreateObject("WScript.Shell")

retCode = oShell.Popup("Open Logfile?", 10, "No Reply from host", 4 + 32)

Select Case retCode
case 6
CreateObject("WScript.Shell").Run "testpingme.txt"
case 7, -1
WScript.quit(1)
End Select
Now when I try to call this vbs script from the batch, after the subroutine in label3 the rule applies only to the last device in the file. And it shows me the logfile but it is to early as the filename renaming is not finished yet.
with this line: Code: [Select]IF %ERRORLEVEL% EQU 1 cscript yesno.vbs
Now my question, How can I do a check when the subroutine is finished and if there where (one or more) errors during the routine to show me this messagebox and open the file once it's ready?

Or does someone know if there is another approach to achieve the same result (probably it would even be better to show me a summary of errors at the end of the routine including an option to open the logfile)

Thanks for helping out! Quote

[PM]
exit /b  will return to main program next line

Thanks for the tip, where did you INTEND to insert it?
I don't see why I should return anywhere, or am I missing something.Who did you recieve a PM from ? ?PM stands for private message, so let's keep that private.

I PRESUME that that person has good reasons why not posting in public. He has the right to do so and I think we should respect that. What does it matter anyway?....Do as you like...

I have a good reason for asking.Okay, I'm still not with you but nevertheless...
Do you have any suggestions?If you want help privately then do it through some other means.  This is a help forum.  All answers to a thread need to be posted here.  Makes absolutely no sense to get some of your help from a PM and some of it here in your thread.what the

Why do you think I post my question on this forum? I didn't pm myself to give this suggestion, some other guy did. I was just being open by posting his pm to the public as I figured it could also be useful  to others. and I wanted some more explanation on his thought.

so why are you dissing me with this shite, I just want some advice from experienced users, but it seems to me they aren't here..... the room is full of old tarts! Quote from: osvikvi on February 22, 2012, 09:31:12 AM
the room is full of old tarts!

Yeah, that's a really good way to get people to help. Labeling the whole based on the replies of the few. Please forgive me if I'm not my usual helpful, explanatory self.

If you want one check after the list of ips has run through, try this:

Code: [Select]ping -n 1 %1
IF %ERRORLEVEL% EQU 1 (
  ECHO    **  # %1 - %2 is not responding     ** >> %tnm%
  mplayerc.exe /minimized /play /close "dingdong.wav"
  MSG "%username%" /TIME:600 %2 - %1 is not responding
  set erry=1
)
Then after your REN command in label3, put:

Code: [Select]ren "testtemp.txt" "testpingme.txt"
if "%erry%"=="1" (cscript yesno.vbs)
goto :eof
Alternatively, try this in your subroutine if you want it to check after each time the subroutine runs:

Code: [Select]ping -n 1 %1
IF %ERRORLEVEL% EQU 1 (
  ECHO    **  # %1 - %2 is not responding     ** >> %tnm%
  mplayerc.exe /minimized /play /close "dingdong.wav"
  MSG "%username%" /TIME:600 %2 - %1 is not responding
  cscript yesno.vbs
)
Next time you are looking for help, try not to call the person/people capable of helping you "old tarts." Usually, it doesn't get you the results you are hoping for. Keep it clean...we have Members of all ages here. Quote from: osvikvi on February 22, 2012, 09:31:12 AM
and I wanted some more explanation on his thought.
I have no idea what they were thinking.  I am not omniscient. Maybe you should ask the person to post here and explain themselves better.That's why I posted his pm here in the open. I couldn't reply to his pm for some reason.

Anyway, Thanks Raven19528 I'll give it a try when I return to the office. to set things straight I said "it seems..."

Sorry Patio, you may clean-out the irrelevant stuff, I would do it myself but I can't edit my posts.. Thanks for your supportNo problem...HOORAY works like a charm, thanks Raven19528.

As usual the solution is simple, you just have to come up with it!
 Now I have only one messageprompt and at the end of the cycle. giving me the option to open the logfile containing the errors.

Maybe I can show these errors in the vbs messagebox, is there any way to port %erry% to another script?

Thanks a lot Quote
is there any way to port %erry% to another script?

I hope it's not bad manners of me to jump in here, but you can pass parameters to a VBScript on the command line like so

(I always use //nologo)

cscript //nologo Scriptname.vbs "p1" "p2" "p3" (etc) (quotes are stripped in the script)

and in the VBScript there is an object called WScript.Arguments that acts like a zero-based array so that:

WScript.Arguments(0) will be p1
WScript.Arguments(1) will be p2
WScript.Arguments(2) will be p3

You are not limited to 9 parameters like in batch, but total command line string length cannot exceed 8192 characters.
748.

Solve : Send an ENTER command to an Executable program?

Answer»

I hope this has not been already answered in another THREAD, but here's what I really NEED to do.

I set up Microsoft's "Disk Cleanup" program to run in extended mode, for all my customers and put a shortcut to it on their desktop as a part of a weekly (not weakly) maintenance routine.

Here's the command line to run the program:
%SystemRoot%\System32\Cmd.exe /c Cleanmgr /sageset:65 & Cleanmgr /sagerun:65

And here's the batch file to run the command:

Echo off
cls
%SystemRoot%\System32\Cmd.exe /c Cleanmgr /sageset:65 & Cleanmgr /sagerun:65


But somehow, I need to get the ENTER Keypress into the program so the user doesn't have to manually click the [OK] button.

I've piped Y and N to programs before but never the "ENTER" key.
Any help would be greatly appreciated.  (I want to stay within batch file programming if possible)

What OS?


XP Pro, Vista, Win-7 or Win-8  Eh?

Batch language is pretty much the same with all of them.I would assume that is happening because you are using sageset.As far as I know, there is no generic way to pipe keypresses to Windows GUI programs. If the program was written to accept them, that's one thing, but if it wasn't, then you can send all the CRs you LIKE via a pipe

echo. | program.exe

or via a temp file using redirection

echo. >crlf & program.exe
and they will be ignored.

Cleanmgr.exe APPEARS to fall into that category pf program. I saw a post on the MSFN forum which said that there is no way to get cleanmgr to run silently. I suspect that this may be by design; that it needs 2 clicks on "OK" buttons by a logged-in user to run it. Possibly for security reasons. For a start, cleanmgr /sageset:NN modifies the registry, and I can also see how cleanmgr could be used by the ill intentioned to cover their tracks.

Quote from: TheShadow on February 19, 2012, 02:36:16 PM

XP Pro, Vista, Win-7 or Win-8  Eh?

Your "customers" run all those operating systems? Including unreleased ones? Anyhow, cleanmgr is not the same on all those OSs. Vista and 7 have new switches compared to XP.

Quote
so the user doesn't have to manually click the [OK] button.

But they are "manually" clicking the shortcut icon; their hand is on the mouse, what difference will another click or two make?

If you did a reg QUERY you could check to see if the registry entry exists already.  If it does then you don't need to use the SAGESET. Ok, I guess some clarification is needed.

My customers who I set up a weekly maintenance routine for, do use XP, Vista and Win-7 and I'm personally testing Win-8/DP, so I'm trying to find things that will work across multiple OS's.

But what I'd like to do is set up Disk Cleanup to run from a batch file, not from a desktop shortcut, so I don't have to depend on an 86 yr old gramma to do her weekly maintenance, which many of them won't.
I'd like for it to run without user intervention, just like my XPCleanup.bat program, which I do put in the Startup folder, for a little daily maid service.
I'd like to be able to add Disk Cleanup to the end of my own XPCleanup.bat program.

It's just that Disk Cleanup addresses some System Folders that I've not previously identified, to add them to my cleanup batch file.  The one I use on my own PC, is customized for my own use and has over 40 lines in it now.
When I do a cleanup, I really do a CLEANUP!
I don't mess around with it!

I did figure out how to empty the trash cans (recycle bins) with a batch file, so now I empty those too.

I'm just trying to do the best possible job for my customers, that I can do with the very minimal things for them to do.

My goal (someday) is for a totally self maintaining PC.  I use AV and AS software that updates and scans by itself every day and I have my Cleanup batch file that runs on every boot up, so the user can enjoy their PC without having to worry about the maintenance aspect of it.

thanks for all your help,
The Shadow  Quote from: Squashman on February 19, 2012, 04:19:30 PM
If you did a reg query you could check to see if the registry entry exists already.  If it does then you don't need to use the SAGESET.

Well, you're on the right track.  If I manually run sageset, then I can run Sagerun as many times as I like and still wont have to change anything.  Good point!

Yous guys have got me thinking outside the box, and for this 68 year old, that's a GOOD THING!

Cheers Mates!
The Shadow  I'm back!

Salmon Trout, if memory serves me, you've helped me out before and sure enough you've done it again.

echo. | program.exe

This suggestion of yours works perfectly.

I put the Disk Cleanup command at the end of my XPCleanup.bat  batch file and it runs without user intervention.
I did remove sageset from the command line, since the parameters only need to be set once and I can do that when I first install the batch file for my customer.

Moving right along................

Many Thanks!
The Shadow B)The reason it runs without user intervention is because you took the SAGESET out.I'm getting the WHOLE picture now. 

No, it runs automatically because of the help given to me by Salmon Trout to pipe the CR into the program when it runs.
That was a huge help that I may be able to use again.

Taking out Sageset was just a part of my learning curve.
You still have to run cleanmgr with sageset at some point to set up the choice for what things will be removed.

I know I'll get another argument about this, but I always check everything, but, Office Setup Files, Setup LOGS and Compress old files.  After I run my registry tweaks, Compress old files is not even in the list.

I'm working on a batch file to run from my Utilities disk, to install the Extended version of Disk Cleanup, into the Startup Folder,  after first running cleanmgr with sageset, to set the parameters for later running cleanmgr with sagerun.

I always try to automate the install process as much as I can to save valuable time, while at a customer's home.

I have it nailed down now.  Case Closed!

Thanks for all the help,
The Shadow 

PS: Now that I have the process nailed down for XP, I'll be working to make sure it works as well in Vista and Win-7 and Win-8.

Quote from: TheShadow on February 19, 2012, 05:02:17 PM

echo. | program.exe


Once you have done the sageset part, subsequent runs of cleanmgr /sagerun:NN should run without you doing this. (I just tried it)
I've created a batch file, to install my new XPCleanup batch file into the Startup folder.  At the end of my XPCleanup batch file is the line to automatically run Disk Cleanup (cleanmgr.exe) in the automatic mode.
Like you said, in my install batch file, I run cleanmgr with sageset to set up the things to delete and then when I run cleanmgr with only the sagerun switch, it deletes only what was previously set up with sageset.

I can minimize my XPCleanup batch file when it runs, but Disk Cleanup still pops up on-screen and runs without the user having to press the obligatory 'OK' button.  I'd rather not actually see Disk Cleanup at all, but that's OK.  I can live with that.
It's neat, clean and definitely helps to keep a PC clean and running at peak performance.
I've been working on my Cleanup.bat program since the '98 days and it's still a work in progress.  Every time a find a new hiding place for junk files, I add that location (path) to a new line in my Cleanup batch file.

This is just one little step in a whole litany of things I do to set up or tune up a PC.
My goal has been and is still to set up a PC to run at maximum efficiency from one year to the next with little or no hands-on maintenance.  Because most users just Won't Do It.

The build-up of JUNK or Crapola as I like to call it, is one of the biggest problems in any PC.
It loads up the hard drive, slows down all scans and can greatly increase the time and space to do a backup.

One of my favorite quotes is "Minus CRUD is COOL!"

Thanks again,
The Shadow B)Shadow, I can't get the pipe to work when using SAGESET.  Not sure how you are getting it to work.
Salmon Trout does it work for you when using SAGESET? Quote from: Squashman on February 20, 2012, 06:59:34 AM
Shadow, I can't get the pipe to work when using SAGESET.  Not sure how you are getting it to work.
Salmon Trout does it work for you when using SAGESET?

No; see my reply above (Post 4 of this thread). You cannot send a CR to cleanmgr via a pipe. When using /sageset it requires the OK button to be pressed. When /sageset has been used and the registry entry has been saved, then cleanmgr /sagerun:NN does not need ENTER to be sent to it, and will ignore any that are sent.
749.

Solve : I've forgotten DOS commands, please help.?

Answer»

I'm trying to change the attributes of a read only file by using MS DOS. The commands are

c:/WINDOWS/system32/macromed/flash/flashutil11e_activex.exe

& this is the part that I become stuck. I know that the command is attrib/-R but I can-t remember the syntax that goes with it. Can anyone help please. It's been a long time since I used this system.
Best wishes,

RobHere's a good link

http://www.google.com/search?q=attrib+command
Try Norton Utilities FA.EXE (File Attributes)

THANKS for help, all fixed. Quote from: jimschel on FEBRUARY 17, 2012, 01:29:44 AM

Try Norton Utilities FA.EXE (File Attributes)

Not everyone out there has Norton... Quote from: patio on February 17, 2012, 05:59:13 AM
Not everyone out there has Norton...

And nobody in their RIGHT mind would use 16-bit DOS disk utilities within a windows environment, for any purpose.
750.

Solve : delete first n lines from a file?

Answer»

hi all,

can someone help me in writing a batch program, which deletes first n lines from a file and place the remaining content in a new file.

thanks in advance.
Code: [Select]FOR /F "skip=5 tokens=* delims=" %%G in (Myfile.txt) do echo %%G>>NewFile.txtIf you till tell me the maximum length of the a line, I can make you a quick program that will let you enter the number of lines to skip and then willl copy the rest of the file.

Quote from: jimschel on February 17, 2012, 01:33:16 AM

If you till tell me the maximum length of the a line, I can make you a quick program that will let you enter the number of lines to skip and then willl copy the rest of the file.
That seems kind of limited if you ask me.
Granted the cmd processor is limited to 8192 bytes to assign to a variable but what are the odds of the lines being that long.A For loop will probably not copy blank lines.   Use the More command with the +n switch. Quote from: Dusty on February 19, 2012, 11:52:49 PM
A For loop will probably not copy blank lines.

Or ones starting with a space or semicolon, I think. And poison characters will STOP the script dead.

Barring any line starting with a colon this will work.  I can change the code as well if the file has a line that starts with a colon.
Input
Code: [Select]Line:1
Line:2
Line:3
Line:4
Line:5
Line:6 next line is blank

Line:8 next line has special characters
#[email protected]#$%^&*()+<>"':!%%!
Line:10Script
Code: [Select]echo off

for /f "skip=5 tokens=1* delims=:" %%G in ('type "myfile.txt" ^| findstr /n "^"') do echo.%%H>>myfile_new.txtOutput
Code: [Select]Line:6 next line is blank

Line:8 next line has special characters
#[email protected]#$%^&*()+<>"':!%%!
Line:10Keeping to the KISS principle:

Code: [Select]more +n myfile.txt > newfile.txt
Quote from: Dusty on February 20, 2012, 11:11:05 PM
Keeping to the KISS principle:

Code: [Select]more +n myfile.txt > newfile.txt
As far as I can tell that will not work if the number of lines in the FILES exceeds 65,534.  Which most of mine do. I do data processing for a living. On the 65,535 line it outputs -- More (4%) -- to the output file and the batch file pauses. Quote from: Squashman on February 21, 2012, 05:42:01 AM
As far as I can tell that will not work if the number of lines in the files exceeds 65,534.  Which most of mine do.

skipline.vbs

Code: [Select]Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
ReadFileName  = wscript.arguments(0)
LinesToSkip   = wscript.arguments(1)
WriteFileName = wscript.arguments(2)

' for demo purposes; can delete
'--------------------------------------
StartRead = Timer
'--------------------------------------

Set ReadFile  = objFSO.OpenTextFile (wscript.arguments(0),  ForReading)
strText = ReadFile.ReadAll
Readfile.Close

' for demo purposes; can delete
'--------------------------------------
EndRead = Timer
ReadTime = EndRead - StartRead
StartSplit = Timer
'--------------------------------------

ArrayOfLines = Split(strText, vbCrLf)

' for demo purposes; can delete
'--------------------------------------
Endsplit = Timer
SplitTime = Endsplit - StartSplit
StartWrite = Timer
'--------------------------------------

Set Writefile = objFSO.CreateTextFile (WriteFileName, ForWriting)
For j = LinesToSkip To UBound(ArrayOfLines)
Writefile.writeline ArrayOfLines(j)
Next
Writefile.Close

' for demo purposes; can delete
'--------------------------------------
EndWrite = Timer
TotalTime = EndWrite - StartRead
WriteTime = EndWrite - StartWrite
wscript.echo "Number of Lines in file: " & UBound(ArrayOfLines)
wscript.echo "Read file in             " & ReadTime  & " sec(s)"
wscript.echo "Split file in            " & SplitTime & " sec(s)"
wscript.echo "Wrote output file in     " & WriteTime & " sec(s)"
wscript.echo "Total time taken         " & TotalTime & " sec(s)"
'--------------------------------------

Code: [Select]C:\Batch\Test\>type 20lines.txt
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11
This is line 12
This is line 13
This is line 14
This is line 15
This is line 16
This is line 17
This is line 18
This is line 19
This is line 20

C:\Batch\Test\>cscript.exe //nologo skipline.vbs "20lines.txt" 3 "outlist.txt"
Number of Lines in file: 20
Read file in             0 sec(s)
Split file in            0 sec(s)
Wrote output file in     0.0078125 sec(s)
Total time taken         0.0078125 sec(s)

C:\Batch\Test\>type outlist.txt
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11
This is line 12
This is line 13
This is line 14
This is line 15
This is line 16
This is line 17
This is line 18
This is line 19
This is line 20


Note: the load and split times for the small file are too short for the VBScript timer function to measure.

Now for some real files...

Clist.csv has nearly 300,000 lines like this and is 36 MB in SIZE

"CreationTime","Length","FullName"
"04/06/2011 08:43:43","4226277376","C:\pagefile.sys"
"02/06/2011 21:08:43","3169705984","C:\hiberfil.sys"
"05/03/2011 08:14:10","2376366352","C:\Documents and Settings\Mike\X15-65732.iso"
"05/03/2011 08:14:10","2376366352","C:\Users\Mike\X15-65732.iso"
"07/07/2011 20:39:09","1818939392","C:\Users\Mike\AppData\Local\Microsoft\Windows Virtual PC\Virtual Machines\Windows XP Mode.vhd"
"07/07/2011 20:39:09","1818939392","C:\Documents and Settings\Mike\AppData\Local\Microsoft\Windows Virtual PC\Virtual Machines\Windows XP Mode.vhd"

Code: [Select]C:\Batch\Test\>cscript.exe //nologo skipline.vbs "Clist.csv" 3 "outlist.txt"
Number of Lines in file: 294457
Read file in             1.953125 sec(s)
Split file in            0.6328125 sec(s)
Wrote output file in     3.632813 sec(s)
Total time taken         6.21875 sec(s)
Big-Clist.csv has nearly a million lines and is 108 MB in size

Code: [Select]C:\Batch\Test\>cscript.exe //nologo skipline.vbs "Big-Clist.csv" 3 "outlist.txt"
Number of Lines in file: 883371
Read file in             5.164063 sec(s)
Split file in            5.390625 sec(s)
Wrote output file in     10.95313 sec(s)
Total time taken         21.50781 sec(s)
System: AMD Phenom II 3.0  GHz 4 GB RAM drive: 7200 rpm SATA

Nice Job. Vbscript has always been one of those things I have just refused to learn.In my script above, is this:

Code: [Select]Set ReadFile  = objFSO.OpenTextFile (wscript.arguments(0),  ForReading)
That will work, but for consistency it should be

Code: [Select]Set ReadFile  = objFSO.OpenTextFile (ReadFileName,  ForReading)
Quote
Vbscript has always been one of those things I have just refused to learn.

It's not all that HARD, especially if you can use it to do useful things, and it can do so much more than batch. Of course Powershell is the way to go nowadays...
I started pushing myself to use Powershell 2 years ago and then I went on vacationand when I got back to work I said screw it. But it made me realize that object oriented programming is pretty awesome. I was even making gui's with my Powershell scripts.