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.

8701.

Solve : Batch Problems and Executing Files with spaces in path?

Answer»

So I'm working on a batch file to help automate rather large repetitive install. The problem is that Start is unable to find the file for some reason and in general absolute pathing hasn't been working. I'm at somewhat of a loss as all the usual suspects don't appear to be the problem. I'm running Batch from a Windows 7 Command Prompt. Any ideas?

Code: [Select]Install.bat
@echo off

:start
cls
set /p answer=Do you wish to Install updates? [Y/N]:

if %answer% == Y goto install
if %answer% == y goto install
if %answer% == n goto exit
if %answer% == N goto exit



:install
REM // Used these since absolute path was causing problems
cd Win7
cd x64

echo Installing. Please Wait . . . . . .

FOR /F "eol=; tokens=1,2,3* delims=," %%i IN (list.txt) DO (
set /p t=Installing %%i . . . . . . . < NUL
Start /wait "" "%%i /norestart /quiet"
echo Success!!
)

:exit
exit

:shutdown
REM shutdown /r /f /t 0
REM set /p answer= Do you wish to Reboot? [Y/N]:

list.txtCode: [Select]"E:\Maintenance\Patches and Updates\Win7\x64\NDP40-KB2416472-x64.exe"
"E:\Maintenance\Patches and Updates\Win7\x64\Windows6.1-KB958488-v6001-x64.msu"Make a simple test of critical parts of the code.
Quote

FOR /F "eol=; tokens=1,2,3* delims=," %%i IN (list.txt) DO (
set /p t=Installing %%i . . . . . . . < NUL
Start /wait "" "%%i /norestart /quiet"
echo Success!!
)
You need to verify this block of code with a simple test. Make a dummy list of file names that are just 'stubs'. A stub is just a test program that does nothing. You want to see what happens just going through a list of files that do nothing. Never try to use a dubious block of code until it has been really verified. Unless you are a Genius. In which case you would not need help. The FOR /F thing is among the most difficult tools in DOS batch.
I've tested and debugged it extensively. The file list.txt (bottom op) is my stub file. the FOR part works perfect the trouble happens when I add the start command in the loop.

Here's a summary of what I have done up to present (~ 18 hours, "What can i say.. i am stubborn").

Tested with echo as only command in loop, displays variable %%i no problems for entire stub.
Add Start Into the Mix, Opens new Command Prompt at specified directory. --Not what I was expecting
Added "" to the front of start after a little reading and received error invalid switch /quiet /norestart. --Progress!
Added " " needed to be around the entire STATEMENT after /wait and switches.
30 minutes of work leads me to my current state of output at "cannot find E:\Maintenance\Patches and" --smack Brickwall.
OP was posted sometime ~hour seven or nine, lost track of time as the sun was rising and sleep deprivation was kicking and you can bet my coworkers were peaches today

The weird thing is echo runs perfectly and I have double quotes surrounding not just the statement of the start, but ALSO around the path/[file].exe/msu which should deal with issues of long file names but apparently doesn't.

In retrospect I should have just written a perl script up to do what I needed done, but I hadn't programmed in batch before and thought it would have been a nice challenge of my programming skills. Oh well, C'est la Vie.
I see you have used the set /p ...
Code: [Select]FOR /F "eol=; tokens=1,2,3* delims=," %%i IN (list.txt) DO (
This line looks a little odd, considering what you appear to want to do.

The delims block...

Code: [Select]"eol=; tokens=1,2,3* delims=,"
says

Code: [Select]eol=;
consider a semicolon to be the end of line marker, that is, override DEFAULT behaviour which is to IGNORE lines starting with ;

Code: [Select]tokens=1,2,3*
Split the line into 3 delimited tokens: %%i (explicit) %%j, %%k (implicit) plus the rest of the line %%l (implicit) (that's a lower case L)

Code: [Select] delims=,
Set the token delimiter to be a comma

Since your example test.txt does not contain any lines that start with a semicolon, or have comma separated values, I don't quite see why you are doing this. The FOR /F command will pick up the entire line, but only because none of the things envisaged in the delims block are present!

You appear to want to take the whole line so you may as well do this

Code: [Select]FOR /F "delims=" %%i IN (list.txt) DO (
This delims block...

Code: [Select]"delims="
...means "set the only token delimiters to be the start and end of the line"

However, I see that the paths and filenames that you show in test.txt are enclosed in double quotes. The FOR construct will pick these up and they will be included in the string to which %%i expands.

When you add further quotes fore-and-aft in the Start /wait line I believe you are causing the command to be parsed in a way otherwise than you intend.

One of the variable modifiers you can use with FOR metavariables of the %%x type is the tilde ~ which removes enclosing quotes (if present).

So try this - I have not got any KB files to test it on but I have tried others (.txt)

Code: [Select]@echo off
FOR /F "delims=" %%i IN (list.txt) DO (
set /p t=Installing %%i . . . . . . . < NUL
Start /wait "" "%%~i" /norestart /quiet
echo Success!!
)



Each command has its own sometimes extensive documentation which you can see by typing the command followed by a space and /?

e.g.

FOR /?
Start /?







[Update]

The above seems to test out OK... the format for START in these circumstances is: quote the program drive\path\name and then pass the parameters:

start /wait "Window Title" "D:\Path\with spaces\program name.exe" /PARAM1 /PARAM2 /PARAMn

"Window Title" can be (and usually is) a null string ""

Code: [Select]FOR /F "eol=; tokens=1,2,3* delims=," %%i IN (list.txt) DO (
Initially I was using semicolons in my stub file, but having the program ignore them was more trouble than not using them at all. Since the loop was operating correctly I neglected to change the working part until I had the rest of the pieces working.

Code: [Select] delims=,"
I was planning on splitting the drive, path, file into three variables so I could use them individually elsewhere more readily and tighten up the code but I never got the core functionality running properly so that fell by the wayside. (i.e. echoing filename .... installed! ).

As the script is now, it fails at each iteration of the start command. Using
Code: [Select]START /wait "" "%%i /norestart /quiet" Where %%i = "E:\Maintenance\Patches and Updates\Win7\x64\[file].msu" in list.txt
The output is an Alert Window (Title=E:\Maintenance\Patches) 'Windows cannot find "E:\Maintenance\Patches'. Make sure you typed the name correctly and then try again."

Its not displaying the full correct path, cutting off where the spaces are in the long path name, /Patches and Updates/, which leads me to THINK its the long file name thats causing problems. I thought that correctly quoting would have dealt with that but apparently not.


Update: Changed Working Directory to test whether it was the Patches and Updates -> Patches and still same output. Something else is going on here than long path.
8702.

Solve : Generating a Formatted File List?

Answer»

So I'm working on a batch file that will GENERATE a list of all files in the current directory with absolute path ready for input into another script.
Here's what I've got so far.

list.bat
Code: [Select]@ECHO OFF
DIR /B /A:-D > temp.txt
FOR /F "tokens=1" %%i IN (temp.txt) DO (
ECHO %~d1,%~p1,%%i >> list.txt
)
del temp.txt

The problem I am having is it runs perfect so long as list.bat is in the same directory as the other files to be listed.
So for instance lets say I move list.bat to C:\Windows\ so I can call it from anywhere on the computer.
I go to C:\Maintenance\Patches and Updates\, and then run list.bat
Instead of getting C:,\Maintenance\Patches and Updates\,[File] I get an output of C:,\Windows\,[File]. Any Ideas?
Also on a more minor note, temp.txt is added to the LISTING for some REASON, anyone KNOW why?Update: Ok So anyone know why list.bat ./ causes it to work properly and how I can implement that into the script so I don't have to type it with the batch file every time? Also still TRYING to figure out how to prevent temp.txt from going into the text file.list.bat

Code: [Select]@ECHO OFF
DIR /B /A:-D > temp.txt
FOR /F "tokens=1" %%i IN (temp.txt) DO (
IF "%%i"=="temp.txt" ( echo. ) ELSE (echo %~d1,%~p1,%%i >> l.txt)
)
del temp.txt
It works.

8703.

Solve : batch script dies after first call to another different batch script?

Answer»

I have a script that basically calls another bunch of scripts in sequence. I don't care if any of them fail -- I want the script to continue.
Unfortunately, it is not. Can anything be done? Here is the basic gist:

CD C:\really\long\path\
clam

CD C:\another\really\long\path
clam

CD C:\yetanother\really\long\path
clam

After the first "clam", it just stops. "clam.bat" is a simple script that's stored in each directory with specific stuff to do.

Thanks,
use CALL clamthat was the first thing i tried to no avail.

do the clam.bat's call any other batch files?It would be helpful if you showed us the contents of 'clam', but in any case you need to use the 'call' statement if you expect a RETURN to the caller (the batch file you posted).

Code: [Select]CD /d "C:\really\long\path\"
call clam

CD /d "C:\another\really\long\path"
call clam

CD /d "C:\yetanother\really\long\path"
call clam

It might also be wise to turn echo on in 'clam' and any other batch files referenced. This will let you see how the file executes at all levels.

ok. i'll try the "CALL" thing and "ECHO ON" and POST the contents of clam.bat LATER today.
Right now -- i'm at my other job for the next 8 hours.

thanks for all the help everyone.ok -- turns out it was a nestled script call without the "CALL". Modified. Reran. Worked.

Thanks, all.Quote from: whale on MARCH 20, 2011, 11:49:23 AM

What is a "nestled script call?" Show the code and output.

"show the code and output"? When did he become responsible to answer questions after his problem has been solved? Especially when you are questioning the very piece of information that explains his problem.

nestled clearly means nested. I originally suspected one of the "nested" (batch files being called from the main batch) may have an ADDITIONAL batch call that wasn't using call, which is why I asked whether any of the said batches called additional batch files.

Then he discovered the issue so there was no reason to further pursue it.
8704.

Solve : Passing Parameters to a batch file?

Answer»

Hi all,
I have a master file which calls another batch file like below:

Call "C:\CmdDest\CopyFiles.cmd"

pause

The CopyFiles.cmd calls this:
xcopy "C:\Users\images\*.*" "C:\Program Files\images" /y
pause


xcopy "C:\Pics\*.*" "C:\Program Files\Pics" /y

pause

What I would like to do is INSTEAD of hard coding the C:\Users\SunGard Branding\images\*.*, C:\Program Files\images etc I would like to PASS these as Parameters from the Master file to the Child batch file...

Please help me...Have you tried:

Call "C:\CmdDest\Copyfiles.Cmd 'C:\Program Files\Images' 'C:\Program Files\Pics' "

Batch parameters are saved to the variable %1,2,3,4,5,6,7,8,9 and for more than 9 you need to use SHIFT depending on OS. (i.e. OS+Command Prompt or MS-DOS)
and

xcopy "C:\Users\images\*.*" %1 /y
pause

xcopy "C:\Pics\*.*" %2 /y
pauseWhen I do this:


Call "C:\CmdDest\Copyfiles.Cmd 'C:\Program Files\Images' 'C:\Program Files\Pics' "


It SAYS the filename, directory name or volume lable syntax is incorrect

please helpCall "CopyFiles.CMD" Param1 Param2

CopyFiles.CMD
echo %1, %2

Output:
Param1

Looks like on my version it only passes the first variable Param1 to %1, don't know why it doesn't pass more than a single parameter.

Update: You Could pass a single string and have CopyFiles.CMD parse that into two variables after the fact with string manipulation but thats more of an advanced topic and I still haven't gotten all the kinks out short of trimming a known part of the string out using set str=%str:~4% to assuming the first four characters need to be trimmed out.Try:
Call "C:\CmdDest\Copyfiles.Cmd" "C:\Program Files\Images" "C:\Program Files\Pics"

8705.

Solve : Differences between %var and %~var?

Answer»

Anyone know what the differences are between those for batch files. I've SEEN some examples where they are used but haven't been able to figure out EXACTLY what's going on as it seems different commands handle it differently (i.e. FOR). I'm trying to figure out a way for trimming out a portion of a string read in from a file using the for command. I'm just having trouble finding any documentation on the differences between %~var and %var, obviously there is a difference as running
Code: [Select] set str="cmd politic"
ECHO.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str% Works correctly in trimming " " out. THANKSI told you what the tilde ~ character did 4 days ago. It seems you don't read posts very carefully.

Quote from: Me, on 18 March

One of the variable modifiers you can use with FOR metavariables of the %%x type is the tilde ~ which removes enclosing quotes (if present).
8706.

Solve : Using Conditionals in FOR Loop?

Answer»

How do I GO about USING conditionals within a for loop. I've read that the problem I'm running into is because the IF statement is INTERPRETED before the FOR Loop but haven't found a workaround yet.

Here is what I want a BATCH file to do. Check File set flag variables based on %%i %%j

Code: [Select]@echo off
IF EXIST C:\temp.txt (
for /F "tokens=1,2 delims=," %%i IN (C:\temp.txt) DO (
if %%i==1 (
if %%j==x86 (
set x86=1
set reboot=1
)
)
)
)
echo %x86%
Unfortunately the flags never get set.Verify the content of c:\temp.txt
C:\temp.txt:

Code: [Select]1,x86
Batch (as above) output:

Code: [Select]1

8707.

Solve : how to block internet by using command prompt lines?"?

Answer»

if anyone knows the answer for this post it here.You can use the devcon utility which came with the XP TOOLKIT. If you don't have it, you can download it here. Devcon requires that you know the hardware ID or a partial name with wildcards of the NIC.

I also found some VBScript code in the snippet closet.

Code: [SELECT]Const ssfCP = &H3&

strEnable = "En&able"
strDisable = "Disa&ble"

strNetworkFolder = "Network Connections"
arrConnections = Array("Wireless Network Connection") 'Verify Name of Connection

SET objShell = CreateObject("Shell.Application")
Set objCP = objShell.NameSpace(ssfCP) 'Control Panel

For Each f In objCP.Items
If f.Name = strNetworkFolder Then
Set colNetwork = f.GetFolder
Exit For
End If
Next

If colNetwork.Items.Count = 0 Then WScript.Quit

For Each strConnection In arrConnections
For Each cn In colNetwork.Items
If cn.Name = strConnection Then
Set conn = cn
Exit For
End If
Next

bEnabled = True
For Each verb In conn.Verbs
If verb.Name = strEnable Then
Set objEnable = verb
bEnabled = False
Exit For
End If
If verb.Name = strDisable Then
Set objDisable = verb
Exit For
End If
Next

If bEnabled = True Then
objDisable.DoIt
Else
objEnable.DoIt
End If
WScript.Sleep 3000
Next

Save the code with a VBS extension and run from the command prompt as cscript scriptname.vbs Be sure to verify the name of the connection which you can get by opening "Network Connections" in the control panel. The script will toggle the status of the NIC from enabled to disabled or disabled to enabled.

The script was tested on XP but may need some tweaks for other flavors of Windows.

Good luck.

8708.

Solve : Ooops... I closed it. How do I prevent accidental closure of DOS programs??

Answer»

Hi! I have a RELATIVELY simple .BAT file which calls up a simple command-shell '.exe' program. Is there any code that I can add to my .BAT file that would display "ARE YOU SURE YOU WANT TO EXIT THIS PROGRAM?" in case I accidentally hit the "X" in the top right window (that is, accidentally CLOSING the command-shell window).
Help is greeeeatly appreciated,
--BHThe short answer is "no". If you really need the ABILITY to do this, you shouldn't be using batch.

8709.

Solve : renaming files using a batch file?

Answer»

i have a folder with a lot of photos and i would like to USE a dos batch file to rename all the files in the folder but dont know how to do it.
The RENAMED IMAGES should be numbered to avoid errors. Eg.: graduation_1.jpg,
graduation_2.jpg, etc.Even though this is not by batch as requested...there is a tool out there called Better File Rename that works perfect for this type of purpose.In Windows Explorer, you can highlight all the files (any files, not just images) you want to rename, having FIRST got them in the order you want, then right click the (still) highlighted group of files, choose "Rename". Explorer will prompt you to rename the first file in the highlighted set, and when you complete that, all the others will be renamed in numerically ascending sequence in the format "New FILENAME (1).xyz", "New Filename (2).xyz", etc. If you change your mind you can click Edit, Undo Rename.

(1)

Before



(2)

After

8710.

Solve : Name a txt file with output of command?

Answer»

I don't see a "marked solved" button. this is what I see:

[recovering disk SPACE - old attachment DELETED by admin]I think there is a bug, or possibly you need a certain number of posts before you see the mark solved button. No MATTER, we have ANOTHER satisfied customer. HOPE you stick around.

8711.

Solve : Running ping from a batch file?

Answer»

First, to all who contributed to the batch file and command pages, a big THANK YOU! No programming knowledge at all here, but have made a number of batch scripts to automate things like DATA backups and disk cleanups. Everyone *says* back up your stuff frequently (the puter might not boot next time), but few do. Two clicks on a batch, and all the good stuff is copied to a flash drive in seconds. ECHO: THANK YOU!

OK, time to move past xcopy, del, and rd. XP SP2 preloaded by OEM (who strongly advised *not* to install SP3; not here to discuss that, thanks), both Home and Pro, on laptops with wireless router to high-speed cable modem. Using CMD.exe.

Situation: Sometimes, a Web page will stop responding, as we all know. Lots of reasons. But every once in a while, the reason is that the connection has been dropped, whether by the ISP, the modem, or the router. The *connection between machine and router* never goes down, so it's SOMEWHERE between the router and the Web. Quickest diagnostic is to ping example.com. If it works, it's probably the web server, etc. If not, then either the modem or router has dropped the connection. Reboot them, and all is well.

Here's the problem: You guys and gals have me so spoiled , I don't want to open a command prompt and type all that, although the typing can be automated by auto-text tools. And I'm too lazy to put down the laptop and go into another room to look at the modem and router. Hey, that's part of the goodies of laptops! I'd like a batch file that when 2-clicked, runs the command ping www.example.com. Default parameters are fine. It's only four packets.

Tried with just ping etc., and also with cmd /K for a new window. Allowed TCP/IP Ping command in firewall. What happens: cmd window opens, but it just keeps repeating the command infinitely, and very fast, so I have to close the window. No actual pinging.

Ball in your court. And thanks in advance! (Have I said "thank you" yet?)Your questioning style is so very annoying. Could you try cutting out all this Hey! Yee-har! stuff? Also, as you admit, you are being lazy. Why should we do all your thinking for you? Have you tried writing the batch script yourself? Did you even think of telling us what you have tried already?

Code: [Select]@echo off
ping www.example.com
pause
Wow, you guys are harsh. First post, the user thanks everyone. I've been a volunteer mod at other forums, and it's always nice when someone takes the time to show some appreciation. I don't think I've ever been offended by someone thanking us *too* much. Strange.

Annoying style? People who curse or are snotty are more offensive than those who maybe are a little to friendly or chatty to suit your tastes. I checked the Registration agreement, and there was nothing about being too friendly. Maybe you should amend that.

Quote from: Salmon Trout

Why should we do all your thinking for you? Have you tried writing the batch script yourself? Did you even think of telling us what you have tried already?

Did you not *read* the user's post?

Quote from: Bat Mastersome
Tried with just ping etc., and also with cmd /k for a new window.

He is saying that he already tried the batch file with exactly that: ping www.example.com, which BC_Programmer later suggested. And that he also tried with cmd /k ping www.example.com. And he gave you the result:

Quote from: Bat Mastersome
What happens: cmd window opens, but it just keeps repeating the command infinitely, and very fast, so I have to close the window. No actual pinging.
Did you not *read* that?

Quote from: Salmon Trout
Could you try cutting out all this Hey! Yee-har! stuff?

I searched the OP, and didn't find any use of "Yee-har". So now it's Salmon Trout who's being sarcastic and snotty. Maybe he should be banned.

Speaking of which: *Banned* on the first post, because you don't like his style of writing? Not even a warning or a request to phrase differently? Guess you should have an exact format posted, fill in the blanks, the way you like it, since anything else is apparently unacceptable. We banned people for spam, usually after one warning unless really bad; scamware or malware links immediately; profanity, usually after a warning unless really bad. *Never* because their style of questioning was "personally annoying". 7 billion people in the world, they're not all going to talk and write exactly alike, you know. Saw others here banned on first post because of some little nit. Someone asks you to do their homework or whatever? Point them to the rule about it, matter-of-factly, and keep them as a member for life, instead of banned for life for one mistake. Sheesh.

Wikipedia has among its basic tenets: "Don't bite the newcomer". You guys sure took a GREAT chomp out of this one. Nice job of reinforcing the stereotype of computer people as being rigid, humorless geeks. Oh, and don't bother banning me - I won't come back here *ever*, I promise. And neither will my evil twin, the OP. Have a nice day.

P. S. Since you guys didn't care to answer the question of why the ping command was being repeated endlessly, it was solved another way: auto-text tool (won't spam the name of it, even though it's total freeware). One click on Start, one on shortcut to cmd, one trigger letter ("p") which auto-types the desired command, (enter). Four keystrokes instead of two, and no having to deal with mini-dictators who do on the Web what they can't do in real life. Sad. Good luck. What's all this about people being "banned"? The OP has not been banned that I know of, but then I am not a moderator, just an ordinary member who gave his own personal, non-official opinion. If the OP was indeed banned, it must have been for something else that i don't know about, something more serious than a posting style that I didn't like!


The OP never was and is not banned...
The person who was and had his Posts removed was...maybe that's who former mod is referring to...we all know who that was...
Thanks former mod on all the good advice on running a Forum.
Say hi to Bill for us.Here is a great Network Connection Tester I came across. hope it helps
Code: [Select]@echo off
ECHO Checking connection, please wait...
PING -n 1 www.google.com|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 goto :SUCCESS
IF ERRORLEVEL 1 goto :TRYAGAIN

:TRYAGAIN
ECHO FAILURE!
ECHO Let me try a bit more, please wait...
@echo off
PING -n 3 www.google.com|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 goto :SUCCESS2
IF ERRORLEVEL 1 goto :TRYIP

:TRYIP
ECHO FAILURE!
ECHO Checking DNS...
ECHO Lets try by IP address...
@echo off
ping -n 1 216.239.37.99|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 goto :SUCCESSDNS
IF ERRORLEVEL 1 goto :TRYROUTER

:TRYROUTER
ECHO FAILURE!
ECHO Lets try pinging the router....
ping -n 2 192.168.0.1|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 goto :ROUTERSUCCESS
IF ERRORLEVEL 1 goto :NETDOWN

:ROUTERSUCCESS
ECHO It appears that you can reach the router, but internet is unreachable.
goto :FAILURE

:NETDOWN
ECHO FAILURE!
ECHO It appears that you having network issues, the router cannot be reached.
goto :FAILURE

:SUCCESSDNS
ECHO It appears that you are having DNS issues.
goto :FAILURE

:SUCCESS
ECHO You have an active Internet connection
pause
goto END

:SUCCESS2
ECHO You have an active internet connection but some packet loss was detected.
pause
goto :END

:FAILURE
ECHO You do not have an active Internet connection
pause
goto :END

:END

8712.

Solve : Scripting Tutoring??

Answer»

Hi I was wanting to know how to script, or find someone who can.

I can offer very ROMANTIC THINGS

ANyways..

How would I go about find a scripter?You clearly do not know what "romantic" means. This is the hardware section, which has nothing to do with "scripting", whatever you mean by that. If you have a specific question about a problem you have, then feel free to ask it in the right place. HOWEVER, this is not a free college so maybe you should stop wasting our time?Well I couldn't find where to post it.

Basically I'm looking for a specific script and I'm not sure how to go about obtaining it.Quote from: PillowPrincess1 on March 24, 2011, 02:37:18 AM

Basically I'm looking for a specific script and I'm not sure how to go about obtaining it.

Say what you want the script to do, giving as much details and information as you can. That would be a start. Maybe somebody will be prepared to help you. We are more likely to help people who are writing a script and having a problem, than we are to write a complete script for somebody too cheap to pay for professional help.
Well it's on a site called dovogame.com BTO

I need a script to login, upgrade game stores, collect guild allowance and DONATE. Then do that for 100 different accounts, with different IP.

An I am willing to pay to get this done.Quote from: PillowPrincess1 on March 24, 2011, 03:06:51 PM
Well it's on a site called dovogame.com BTO

I need a script to login, upgrade game stores, collect guild allowance and donate. Then do that for 100 different accounts, with different IP.

An I am willing to pay to get this done.

Well, the scripting help on this completely free forum is more about helping people who are writing a script already and have hit some kind of problem that they need to fix, or who need an explanation of some bit of language syntax. We don't do paid-for stuff as far as I know. I think you would be BETTER Googling or asking around for a more specialized forum than this one.
Ok, thanks..Quote from: PillowPrincess1 on March 24, 2011, 03:06:51 PM
Well it's on a site called dovogame.com BTO

I need a script to login, upgrade game stores, collect guild allowance and donate. Then do that for 100 different accounts, with different IP.

An I am willing to pay to get this done.

Collecting Gold i see...Did this guy seriously just ask us to make him a bot that does his online game for him (wich is probably even against the rules).... oOQuote from: polle123 on March 24, 2011, 03:32:28 PM
Did this guy seriously just ask us to make him a bot that does his online game for him (wich is probably even against the rules).... oO

I did wonder about this... the tone of the initial post kind of made me a bit wary, like they tought we were idiots... but I know nothing about gaming, so I didn't know if what he or she wants is unethical.
8713.

Solve : Bypassing the Dos boot screen?

Answer»

Can anyone tell me how to hide the dos boot screen and going STRAIGHT to my windows login screen?
Thanks
Do you mean you don't want to see the POST? Look in BIOS for an option that says "silent boot" or something similar and ENABLE it.

If you mean something else, please clarify.NOTE:
Turning it off does not have the machine skip this step...you just will not see it...Quote from: patio on March 25, 2011, 06:08:19 AM

NOTE:
Turning it off does not have the machine skip this step...you just will not see it...
So the same thing could by done by keeping your eyes CLOSED until you hear the Windows music?I suspect OP means System Startup, Default OS. HP/Compaq display this for 3 sec. The other OS is the RECOVERY Partition.
8714.

Solve : need help with creating a log file from batch?

Answer»

i SAW a script that there is that command on the script and it worked.
it was: script 0 2>>log.txt

i want it all to be on one script, not to write in the command prompt.
there isn't a way?
There is a DEFINITE failure to communicate.

Nobody is suggesting you write the script at the command prompt (although you can). Use an editor (NOTEPAD will work) to write your script (batch file); save it with any name you like but with a bat extension. Open up a command window, navigate to the directory where you saved your script/batch file and run using the name you saved the script with and redirecting the error output to the log.txt file:

Code: [Select]script 2>>log.txt

I'm not sure what this is all about:

Code: [Select]script 0 2>>log.txt

but the zero is passed as a command line parameter which is not referenced in your script and therefore servers no purpose. This piece of the command 2>>log.txt sends the error stream to the log file.

Have you even tried to run your batch file. Even if incomplete, it's a good idea to at least find any syntax errors and maybe even some logic errors. You've written the logic for menu selections 2 and 3, so test with them and see the results yourself. Better to test as you write rather than wait until the script is 'finished' and then have to slog through all the errors at once.



Of course i have tested it, with a lot of situation.
But will this method 'remmember' all the errors that the script had on run?Quote from: Lwe on March 27, 2011, 09:37:31 AM

Of course i have tested it, with a lot of situation.
But will this method 'remmember' all the errors that the script had on run?

I thought that was the whole point of the log file. Have you checked the contents? If the file is empty after running your batch file, then all is well in Wonderland. If not, you need to backtrack and see where the error came from and how to fix it.

As I already mentioned, one DEFENSIVE piece of code is the unconditional goto you could insert after checking for valid menu selections. Another would be to check if each of the files exists before trying to delete them.

Why is it even necessary to 'remember' the errors? Why not just let them appear on the console, and then fix the code to prevent them? Keeping it simple makes it easier to fix things later.

If you're still having problems, post the name of your batch file and we can discuss exactly how to run from the command prompt. In the meantime I need an adult beverage.



lol.
thanks alot!
8715.

Solve : Some help creating a batch file please?

Answer»

I am currently working on a batch file, and i want it's function to copy .class files into a .jar file. How WOULD I go about doing that?

Would I have to write the script to decompile the jar file into a folder, copy the .class files to that folder then RECOMPILE the .jar file?

Or is there a way I can tell my batch file to inject those class files straight into the jar file?You can use the JAR program which is included with the JDK. Type jar at the COMMAND prompt
for details and examples.

Note: The JDK was put on your path when it was installed. Most likely is located: Java\JDK6\bin

Good luck.
thx, now would i be able to distrubite the batch file even if the client doesn't have the JDK? or would I have to PROVIDE SOMETHING in the folder with the batch file?

8716.

Solve : 1st time in MSDOS?

Answer»

Hi,
I am LEARNING MSDOS programmimg and my 1st assignment is the FOLLOWING.
1. i have to create a batch file.
2. i have to pass the value "year" in my commandline argument.
3. the batch file should use this argument to replace the name of another file prefixing with the value "Year"
4. the file shud read the content of the file and replace all the corresponding year value with the argument passed.
5. appropriate error message shud be providedwhile passing null, anything other than a 4digit year value.

i tried doing this in parts using the help on net but i am unable to do all of this in a single batch file.
can anyone please suggest how to go about this
?The whole point of assignments is to put into PRACTICE what you have learned in class

We cannot be with you when the exam comes, so at least make an attempt and post what you have tried so far.

If you cannot even start, then maybe you chose the wrong course hi....

thanks for that... but i'm neither taking a course not do i have exams..... i've been asked to learn how to rite batch files as a part of my project.
i know programming in oracle but DOs is much different..... and scripting is totally diffrent.

that is the reason y i asked for help, which could help me understand 1 example to further build on my work files.sorry, I misunderstood your use of the word assignment

post the parts you have and we can try to tie them together No issues at all.

the code is used is the following:

set /p "old=old string ? "
set /p "new=new string ? "

for %%A in (TEST.bat TEST1.bat) do (
>new%%A type nul
)
for /f "tokens=* delims=" %%b in (%%A) do (
set "str=%%b"
>>new%%A echo !str:%old%=%new%!
)
when i ran this batch file.....the system would prompt me to enter the existing value and the new value then the content in TEST.bat and TEST1.bat is replaced with the new value and also 2 new files are created prefixed with 'new'
but somehow no when i run this the system gives me an error could not fine the file specified %a.
i remember changing something... but not sure what.

could you help?

i used the following peice of code to PREFIX the name of the file with a command line argument.

echo %1
set A=%1
ECHO %A%
rename TRIAL.TXT %A%_TRIAL.TXT

now i have to combine the 2 and also generate appropriate error messages.

i have to pass an argument in the command line(2011) and then the file name should be replaced from TRIAL.txt to 2011_TRIAL.txt
also inside the TRIAL.txt file where ever there is the value(2010,yyyy,year,yy) should be replaced with 2011.

if at the command line i pass a null value, non-num, alphanumeric, SPECIAL character... the system to prompt me saying i should enter only a valid 4-digit year value.

hoping that you could help me.
This is homework.

You can tell by the context of the questions.

Try doing some research.

8717.

Solve : how to count all files from a perticular directory according to there date & tim?

Answer»

how to count all files from a perticular directory according to there date & time.. Can anyone have solution for this
Currently i am able to count files but not by there specific (user defined) date & time..... I want such code in batch file.... What do you mean "according to date and time"? Do you mean count all the files earlier than or later than a specified date and time? Or all those that have a certain date? Or do not? Please state your requirement more clearly. And state your local date and time format.
Salmon Trout
: Yes i want to search files between to specific data like from 20 Sept 2011 to 22 Sept 2011.....!! & Date format is mm/dd/yyyy & time format is 12Hrs clock..
And one more thing which i forgot to mention is that - i need such code where i can search n no of directories...
CarlCarson
Thanku you Carl however given syntax is not satisfying my need.

please give example of date and time format used in dir like these

09/22/2011 19:46

06/21/2004 05:39 AM

or describe thus

dd/mm/yyyy HH:MM:SS

I require to know if time format includes leading zero for hour less than 10 e.g. 08 and if seconds are shown.
One more question, is the date in the title or are you going off of the date created stored in the file attributes? I think they will both follow the same basic coding, but pulling the information in would be different. Also, if you are pulling the date from the title of the file, is a standard naming CONVENTION used. i.e. Do all of the files start with mm/dd/yyyy title blah.txt?

The basics of the code would create a numeric value out of the date and then compare.
Code: [Select][this should be set within a FOR command]
set FileDate=[however date is defined]
set /a NumYears=!FileDate:~6,4!*365
set /a NumMonths=!FileDate:~0,2!*30
set /a FileDateCheck=!NumYears!+!NumMonths!+!FileDate:~3,2!

[use above calculations to determine the check against numbers for the "threshold" dates]

if !FileDateCheck! lss !HiThresh! (
if !FileDateCheck! gtr !LoThresh! (
set /a NumFiles=!NumFiles!+1
)
)

[after the FOR command ends]
echo %NumFiles%

I probably made that way more complicated than it needs to be, but it does work. There are probably ways for batch to already see dates numerically and compare them accurately, but I have never delved into that so I don't know.

Also, TAKE a look at the variables within variables thread that I started. The final code that I submitted should show the basics on the FOR command that you would want to use for something like this (as far as selecting different directories).

In order to search multiple directories, would the directories be predefined or would you like to input the directories each time you run the program? Please give as much information on what you are trying to do as possible, as Salmon Trout can attest to the fact that it is very difficult to perform psychic debugging (I'm pretty sure it was you who said that or was told that in a previous thread) .Quote from: Raven19528 on September 23, 2011, 12:42:29 AM

if you are pulling the date from the title of the file, is a standard naming convention used. i.e. Do all of the files start with mm/dd/yyyy title blah.txt?

I have a suspicion that they don't... of course it would be much easier if they did.

Quote
as Salmon Trout can attest to the fact that it is very difficult to perform psychic debugging (I'm pretty sure it was you who said that or was told that in a previous thread

It is indeed, but to be fair (I know I've ranted about TLI before) many questioners just plain don't know what information is required. Also a complication is that many people who post answers about batch date/time stuff are under the (grossly) mistaken impression that the whole world uses US format dates and times and that therefore the same chunks of string slicing code will always work regardless.

We don't yet know which date/time the OP wants to use: creation, last access, or last written. I would not bother with last access for various reasons (not enabled on every system, notoriously slow to be updated). The only one I think you can be sure of getting access to is modification time. Not all file systems can record creation and last access times, and not all file systems record them in the same manner. For example, the resolution of create time on FAT is 10 milliseconds, while write time has a resolution of 2 seconds and access time has a resolution of 1 day, so it is REALLY the access date. The NTFS file system delays updates to the last access time for a file by up to 1 hour after the last access.

Anyhow what I would seek to do is get a file date and time as a string YYYYMMDD which could then be treated as a number and therefore used for lss leq equ geq gtr numerical comparisons so that

09/23/2011 would process to 20110923 which is easy enough to implement in batch. If you want HH:MM (and :SS) (and milliseconds!) as well, batch arithmetic won't cut it because you only get 32 bits of precision. So my question to the OP about time format was a waste of time really. Personally I would be using something else like VBScript or Powershell for this.

However I have a distinct feeling that the OP doesn't just want pointers on what to do in their batch file they are going to write, rather they want some person to write the thing for them and then debug it by the psychic method...

Code: [Select]@echo off
setlocal enabledelayedexpansion

set date1=20050601
set date2=20050731

echo Searching for files dated

echo from %date1:~0,4% %date1:~4,2% %date1:~6,2%
echo to %date2:~0,4% %date2:~4,2% %date2:~6,2%

REM Topmost folder to search
cd /d c:\batch

REM /tc creation date
REM /ta last access date
REM /tw last written date

for /f "delims=" %%A in ('dir /b /s /tm') do (

REM Get full drive and path
set filename=%%~dpnxA

REM Get file date
set filedate=%%~tA

REM Uncomment next line if date format is DD/MM/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~0,2!!filedate:~3,2!

REM Uncomment next line if date format is DD/MM/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~3,2!!filedate:~0,2!

if !filedatenumber! geq %date1% (
if !filedatenumber! leq %date2% (
echo %%~tA %%~dpnxA
)
)
)

Code: [Select]Searching for files dated
from 2005 06 01
to 2005 07 31
06/06/2005 20:56 c:\Batch\999nums.btm
10/06/2005 00:07 c:\Batch\bass1.cmd
03/07/2005 20:35 c:\Batch\dvdburn1a.bat
03/07/2005 21:16 c:\Batch\dvdburn2.bat
04/07/2005 17:49 c:\Batch\dvdburn3.bat
27/07/2005 17:29 c:\Batch\INSTALL.LOG
01/06/2005 18:36 c:\Batch\jt-new.btm
23/06/2005 17:41 c:\Batch\jt-url.btm
21/06/2005 17:31 c:\Batch\looptest.btm
09/06/2005 23:05 c:\Batch\mininova-sfu.cmd
01/06/2005 18:36 c:\Batch\newsurls.txt
09/07/2005 15:52 c:\Batch\nopix.btm
24/07/2005 16:43 c:\Batch\RenameAsNumbers.bat
09/07/2005 15:59 c:\Batch\subhide.btm
10/06/2005 00:08 c:\Batch\testme.bas
08/07/2005 20:57 c:\Batch\urlget.bat
07/07/2005 20:54 c:\Batch\number-txt\999nums.btm
03/07/2005 00:50 c:\Batch\tempdir\readme.txt
03/07/2005 00:50 c:\Batch\tempdir\shmnview.chm
03/07/2005 00:24 c:\Batch\tempdir\shmnview.exe
For a GUI approach, I use a free tool called Agent Ransack which offers some advantages over Windows Search


Modularizing your programs, even if it is just using some "::" labels in batch can also help in the long run, as many times you will find that programs you write will have similar components.

Code: [Select]@echo off
setlocal enabledelayedexpansion
set origdir=%~dp0
set NumFiles=0

::Find out the dates you want to find between or use default values
set /p date1=Enter beginning date of search parameters in mm/dd/yyyy format. {default is 01/01/1900} -
if "%date1%"=="" set date1=01/01/1900
set /p date2=Enter ending date of search parameters in mm/dd/yyyy format. {default is 12/31/4567} -
if "%date2%"=="" set date2=12/31/4567

::Set those dates up properly
set date1=%date1:~6,4%%date1:~0,2%%date1:~3,2%
set date2=%date2:~6,4%%date2:~0,2%%date2:~3,2%

::Determine directories
:loop
cls
set /p tardir=Enter full path name of the target directory-
echo %tardir% >> paths.txt
cls
set /p yn1=Would you like to enter another target directory? {y.n}
if /i "%yn1%"=="y" goto loop
cls

::Embedded FOR commands allows the program to process all directories at once
::Using most of Salmon Trout's FOR command with minor adjustments
for /f "delims=" %%B in (paths.txt) do (
cd %%B
for /f "delims=" %%A in ('dir /b /s /tm') do (

REM Get full drive and path
set filename=%%~dpnxA

REM Get file date
set filedate=%%~tA

REM Uncomment next line if date format is DD/MM/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~0,2!!filedate:~3,2!

REM Uncomment next line if date format is DD/MM/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~3,2!!filedate:~0,2!

if !filedatenumber! geq %date1% (
if !filedatenumber! leq %date2% (
echo %%~tA %%~dpnxA >> %origdir%\Results.txt
set /a NumFiles=!NumFiles!+1
)
)
)
)

::Show numerical results, delay, show Results file
cls
echo The number of files in selected directories that match search parameters is %NumFiles%
ping 1.1.1.1 -n 1 -w 3000>NUL ::this is my delay string, others may have different ways they institute a delay
type %origdir%\Results.txt
pause
You have done a great deal to add flesh to the skeleton that I posted, just a couple of things...

1. I made a mistake by putting identical comments before the alternative string slicing lines in the loop

see the fix...

Quote
REM Uncomment next line if date format is DD/MM/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~0,2!!filedate:~3,2!

REM Uncomment next line if date format is MM/DD/YYYY
REM set filedatenumber=!filedate:~6,4!!filedate:~3,2!!filedate:~0,2!

2. It might be an idea to check that date2 is not the same as, or before date1 and if so, emit a message and ask the user to input the start and end dates again...

Quote
::Set those dates up properly
set date1=%date1:~6,4%%date1:~0,2%%date1:~3,2%
set date2=%date2:~6,4%%date2:~0,2%%date2:~3,2%

3. The DIR command which is run by the FOR loop may as well ignore any folders by using the /a-d switch

for /f "delims=" %%A in ('dir /b /s /tm /a-d') do (

4. This is a personal thing, but I really don't like using double colons to start comment lines. They are not a documented or supported part of batch syntax, and being broken labels, they will screw up any structure using brackets that they appear in. (That is they will make the script crash)



Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

D:\users\A511928>d:

D:\users\A511928>cd\

D:\>fcnt.bat
Searching for files dated
from 2011 21 01
to 2011 26 31
Parameter format not correct - "m".

Salmon Trout - I am getting above error while ur file ...There is another way to go about doing this, utilizing the robocopy /l command. The /l option tells robocopy to only list the files that would be copied, which can then be output to another file. Robocopy also has /MINAGE and /MAXAGE options that allow you to do exactly what you are asking. I would need to play around with it a little more, but it is an alternative if you cannot find where the "m" parameter error is coming from.

Also, copy and paste here the exact code you are using so we might be able to see what is causing the error.

Thanks.Try this for a much simpler code overall. Most of your code is actually in gathering the input and error checking at this point.

Code: [Select]@echo off
setlocal enabledelayedexpansion

rem Find out the dates you want to find between or use default values
:dateset
set /p date1=Enter beginning date of search parameters in mm/dd/yyyy format. {default is 01/01/1900} -
if "%date1%"=="" set date1=01/01/1900
set /p date2=Enter ending date of search parameters in mm/dd/yyyy format. {default is 12/31/4567} -
if "%date2%"=="" set date2=12/31/4567
cls

rem Set those dates up properly and check start date is before end date
set date1=%date1:~6,4%%date1:~0,2%%date1:~3,2%
set date2=%date2:~6,4%%date2:~0,2%%date2:~3,2%
if %date1% gtr %date2% (
echo Start date must be before end date
echo Please enter dates again
ping 1.1.1.1 -n 1 -w 3000>nul
goto dateset
)

rem Determine directories [feel free to setup some error checking here as well]
:loop
cls
set /p tardir=Enter full path name of the target directory-
echo %tardir% >> paths.txt
cls
set /p yn1=Would you like to enter another target directory? {y.n}
if /i "%yn1%"=="y" goto loop
cls

rem Here is the big change in the code
for /f "delims=" %%A in (paths.txt) do (
robocopy %%A c:\temp /l /s /MINAGE:%date1% /MAXAGE:%date2%>>Results.txt
)

rem Show Results file
type %origdir%\Results.txt
pause
8718.

Solve : Batch Maintence Script for Sub Directories?

Answer»

Hello,
Im fairly new to cmd scripting and I have been trying to write a script that would go through a all of the sub-directories in a specific folder and run the following script which would save the 10 most recent FILES and delete the rest within that sub folder.

Code: [Select]for /f "skip=10 tokens=*" %%a in ('dir /a:-d /b /o:-d') do del %%a
The ISSUE i'm having is trying to figure out how to have this run in every single sub-directory, If anyone can POINT me in the right direction on how I can SOLVE this issue I would be forever GREATFUL, this is how my .bat file currently looks:

Code: [Select]@echo off &setlocal
set folder=C:\test\
pushd "%folder%"

for /f "skip=10 tokens=*" %%a in ('dir /a:-d /b /o:-d') do del %%a

popd

pauseDeleteme

8719.

Solve : Runas .bat file help?

Answer»

I am trying to set up a .BAT file that allows me to first authenticate me as an administrator by a prompt then re-register some .dll files and FLUSH the DNS. Here is what I have come up with so FAR. Any help would be extremely appreciated.

runas.exe /USER:domanname\myadminname
REGSVR32 msscript.ocx
regsvr32 dispex.dll
regsvr32 vbscript.dll
regsvr32 softpub.dll
regsvr32 wintrust.dll
regsvr32 initpki.dll
regsvr32 dssenh.dll
regsvr32 rsaenh.dll
regsvr32 gpkcsp.dll
regsvr32 sccbase.dll
regsvr32 slbcsp.dll
regsvr32 cryptdlg.dll
REGSVR32 OWSSUPP.DLL
regsvr32 ole32.dll
ipconfig /flushdns

8720.

Solve : Creating Multiple Directories?

Answer»

Monthly I go through a process of creating 36 directories. I thought a DOS batch/command file would be an easier way of doing this than clicking through Windows, multiple times. The naming convention of these directories only changes monthly by the month name and annually by the fiscal year. Here is an example of what I tried.

MKDIR H:\Acct COE\AR Chapter\FY 2012\Maine\SO Maine-Portland\Backup-September 2011
MKDIR H:\Acct COE\AR Chapter\FY 2012\Maine\SO Maine-Portland\Backup-September 2011\Posting Reports

What I got was not what I need. (1) the directories created were created under My Documents rather than drive H: (which is a network drive). (2) rather than 2 directories, as set forth above, I got 10 directories (as a result of the spaces in the drectory names above).

So, I have the following questions:

Using a DOS batch/command file,
- Can I create directories on a network drive?

- If I am able to do so, could you explain what is wrong with the above command or what I need to add to accomplish this.

- If memory serves me correctly DOS directories did not allow for spaces in the directory name (used a lot of hyphens and underscores). Is there a work around?

- If what I'm TRYING to accomplish cannot be accomplished with a DOS batch/command file, is there an alternative approach?

Thanks in advance for your help.Quote from: JPSherwin on September 09, 2011, 10:28:49 AM

Can I create directories on a network drive?

Is it a mapped drive?

Quote
If memory serves me correctly DOS directories did not allow for spaces in the directory name (used a lot of hyphens and underscores). Is there a work around?

(a) If you using a recent version of Windows (2000, XP, Vista, 7) this isn't "DOS".
(b) In the Windows NT family command environment, PATHS, and folder and file names with spaces need quote marks e.g.:

mkdir "S:\Folder 1\Folder 2\Folder 3"

Thank you. Your point of quotes around the path worked. I was able to create the directories.

I'm using XP Pro V2002 SP3. If the batch commands I'm using aren't DOS what are they?

As for the drive being mapped, I believe it is. When I click on the My Computer icon on my Desktop, the drive on which I want to establish these directories is among those listed.

Thank you once again for your help.Quote from: JPSherwin on September 09, 2011, 12:04:55 PM
I'm using XP Pro V2002 SP3. If the batch commands I'm using aren't DOS what are they?

Well, in a nutshell, MS-DOS was (is) an operating system, which has a command interpeter, COMMAND.COM, whereas cmd.exe is the Windows NT family command interpreter.

MS-DOS, sometimes abbreviated to "DOS", is a 16-bit command line operating system introduced in 1981 which ran through versions 1 to 6 (version 6.22 released 1992) and a version 7 which accompanied Windows 95, 98 and ME. It has "8.3" upper case filenames. It has a batch language. Its command interpreter is a 16-bit MS-DOS program called COMMAND.COM.

During the 1990s MICROSOFT also marketed a business-oriented GUI operating system called Windows NT. This also had a command interpreter, called cmd.exe (or CMD.EXE if you like). The batch language was broadly backwards compatible with COMMAND.COM and used similar syntax and conventions. Successive versions of cmd.exe accompanied the NT family (NT 3.51, NT4, Windows 2000, Server 2003, Windows Vista, Server 2008, Windows 7) and its features grew. The version which CAME with Windows 2000 is broadly what we see today. It has a sufficient number of features and commands which are absent from MS-DOS that it is correctly regarded as a completely different environment than COMMAND.COM.

Regarding the network drive issue, you may find this page useful:

http://answers.yahoo.com/question/index?qid=20060921072945AAGOgzH
Quote from: JPSherwin on September 09, 2011, 10:28:49 AM
Here is an example of what I tried.

MKDIR H:\Acct COE\AR Chapter\FY 2012\Maine\SO Maine-Portland\Backup-September 2011
MKDIR H:\Acct COE\AR Chapter\FY 2012\Maine\SO Maine-Portland\Backup-September 2011\Posting Reports

A few things that you can do here to make this work out better for you. First, if at all possible to do so, I would try to change the naming convention if at all possible to use numbered months after "Backup", you'll see why in a minute. Second, it would be a lot easier to have the program prompt for certain things (like what FY it is) and then the rest of it can be hardcoded (much better than having to change the script every month). Anyway, here's the coding for setting up a prompt for the fiscal year:

echo Please enter the current fiscal year
set /p fy=(FY)

This will have the program spit out:

Please enter the current fiscal year
FY |

With the I being where the cursor would be.

Also, if you want to make sure that your putting it in the right location, you can put the following at an early point in the script:

net use H: /delete /y
net use H: [full network location] /persistent:yes

This will delete the network location on H: and then remap it to the H: drive you wish to utilize.

Now comes the time to make the actual directories:

MKDIR "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%date:~10%%date:~4,2%"
MKDIR "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%date:~10%%date:~4,2%\Posting Reports"

You'll notice the coding using the date variable in there as well. This will spit out the date the directory is made in a yyyymm format. So you'll end up with a file named "Backup-201109". You can adjust the layout of the date variables a little, and I'm sure you could likely use an additional piece of code to rewrite the month from numbers to letters if you wanted to. We can help out with that, but it would be up to you whether it is easier to change the naming convention or put in an even more involved piece of code in.I thought on it a little bit and here's how you can make it work:

if "%date:~4,2%"=="01" set month=January
if "%date:~4,2%"=="02" set month=February
...
if "%date:~4,2%"=="12" set month=December

Then where the mkdir commands are:

mkdir "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%month% %date:~10%"
mkdir "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%month% %date:~10%\Posting Reports"

So there you go, hope that all helps.Just in case you were looking for a little bit more automation, here's how you can set your FY without input:

if /i %date:~4,2% geq 10 (
set /a fy=%date:~10%+1
) else (
set fy=%date:~10%
)Salmon Trout

Thank you for the information. I was able to accomplish what I wanted.

Raven19528

Thank you for the suggestion. However, I am not able to change from Month Name to Month Number. It's too engrained with my colleagues.Yes, I work with some of the same types of people. Ones who have been doing things one way for so long that any change makes them scream in outrage or retire.

For the coding, just put together the many small posts and you get the code you are looking for:
Code: [Select]...
net use H: /delete /y
net use H: [full network location] /persistent:yes

if "%date:~4,2%"=="01" set month=January
if "%date:~4,2%"=="02" set month=February
if "%date:~4,2%"=="03" set month=March
if "%date:~4,2%"=="04" set month=April
if "%date:~4,2%"=="05" set month=May
if "%date:~4,2%"=="06" set month=June
if "%date:~4,2%"=="07" set month=July
if "%date:~4,2%"=="08" set month=August
if "%date:~4,2%"=="09" set month=September
if "%date:~4,2%"=="10" set month=October
if "%date:~4,2%"=="11" set month=November
if "%date:~4,2%"=="12" set month=December

if /i %date:~4,2% geq 10 (
set /a fy=%date:~10%+1
) else (
set fy=%date:~10%
)

mkdir "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%month% %date:~10%"
mkdir "H:\Acct COE\AR Chapter\FY %fy%\Maine\SO Maine-Portland\Backup-%month% %date:~10%\Posting Reports"
...

The best thing about the code now is that there is no need for user input so it takes that human factor out of the equation.
8721.

Solve : how can i open telnet port??

Answer»

hello
i want open TELNET PORT of a computer in my privait network with command pormpt.
How can i do it? PLEASE help me
The SYNTAX is telnet open website:port

8722.

Solve : Finding the creator of a document/ folder?

Answer»

What is the CLI command that allows you to view who created a FOLDER or document?There isn't one.
There is: http://malektips.com/xp_dos_0037.html

...sort of. It DISPLAYS the owner of the document or folder. I hope that answers your question.You KNOW, Linux711, you MAY be right. I thought he wanted to know how to get the creator of a Microsoft Office document but I see he MENTIONS folders too.

8723.

Solve : find large file in batch?

Answer»

Hi,

I have a list of files in a DIRECTORY. I need to WRITE code in .bat to find the largest file in the directory and rename it.

I am trying to use the below code

set FileSize=0
set Filename=

for %%a in (%Temp%abc*") do (
if %%~za GTR %FileSize% (
set FileSize=%%~za
set Filename=%%a

)
)


But this is not working out..

Can anybody give some suggestions.

Thanks
AmrutaI also tried to use
for %%a in ('dir /b /os E:Tempabc*') do (

But it is also not giving correct result.Try this
Code: [Select]dir /b /o-s>{temp}
set /P biggest=<{temp}
del {temp}
ren "%biggest%" the_biggest_file_here
Thank you so much...It worked..
I am trying since last 3-4 days...

Thank you so much once again...

BTW...what is temp here.. ?ok, Ill explain here

dir /b /o-s>{temp}
create a directory listing of the directory, the /b means just the filename, the /o-s means sort the list with the biggest first
now send the list into a file called {temp} ....the curly brackets makes these files stand out in a directory listing

set /P biggest=<{temp}
set creates a variable, the /P means wait for the user to type something and press enter, BUT we are redirecting the input from a file, so it will start to read the temporary file, until it hits the first carriage return, when it will stop, the variable %biggest% now holds the first line of the file (which is why we sorted the listing biggest to smallest)

and thats ithere's another way that does not involve a temp file

for /f "delims=" %%A in ('dir /b /os') do set biggest=%%A
echo The biggest file is %biggest%


FOR /f .... treat the dataset (the stuff in the brackets) as a source of lines
"delims=" .... take all of each line
%%A .... the FOR loop variable
('dir /b /os') .... the FOR dataset. The single quotes mean "take the output of this command" line by line (because of /f). The dir sort order is smallest first, biggest last, so that %%A will successively hold each file name. We assign this to the variable %biggest% so that when the loop exits (after the last line output by dir) %biggest% holds the name of the last file in the list.

By using the various dir list order switches you can get the earliest or latest dated file, the smallest or largest, etc.

Developing it a bit...

%%~zA is the file size in bytes

for /f "delims=" %%A in ('dir /b /os') do set biggest=%%A & set size=%%~zA
echo The biggest file is %biggest% (%size%) bytes

example

The biggest file is X15-65732.iso (2376366352 bytes)

With a bit of batch arithmetic you COULD get the file size in GB MB or KB but batch arithmetic runs out of steam at 2G so I wouldn't like to suggest it really.
Salmon ...the solution is working fine...

Thanks for HELPING me outi've a question.
this script is almost what i need but, it must not rename the file but open a explorer.exe

i need a script that check if a file is bigger then 100MB.
if have 10 folders that contains each 2 files (c:\backup\example1.bak & c:\backup\example2.bak)

each file must be bigger than 100MB

if the file "example.bak" is smaller then 100mb, it must open the explorer.exe, so i can check that pad.
if the size is bigger then i must check the next folder

i'm a noob with dosscript and read some script here, but must i use "if exist" or "errorlevel"
can somebody help me pls with a bat file ?

thx
Quote from: Remco on September 28, 2011, 03:46:54 PM

i've a question.

Do NOT hijack somebody else´s thread. Start a new one.

8724.

Solve : why it is not working??

Answer»

i have this script:

Quote

@echo off

if (%1)==(0) goto skipme
echo -------------------------------------------------------------------------- >>logerror.txt
echo ^|%date% -- %time%^| >>logerror.txt
echo -------------------------------------------------------------------------- >>logerror.txt
script 0 2>> logerror.txt
:skipme

set workingfolder=C:\Users\Lior\Hero\ROMS\Myn\Rom Manager
color f0

:menu
cd %workingfolder%
cls
echo.
echo.
echo ---------------
echo Usual Procedure
echo ---------------
echo 0 Start clean
echo 1 Extract rom
echo 2 Add hebrew Fonts.
echo 3 Remove unwanted apps.
echo 4 Edit prop.
echo 5 Add ringtone.
echo 6 Delete unwanted media.
echo 7 zip and sign.
echo 8 Do all.
echo --------------------------------------------------------------------------
echo.
set /p choice=
if %choice%==0 (goto clean)
if %choice%==1 (goto extract)
if %choice%==2 (goto hebrew)
if %choice%==3 (goto apps)
if %choice%==4 (goto prop)
if %choice%==5 (goto ringtone)
if %choice%==6 (goto media)
if %choice%==7 (goto zip)
if %choice%==8 (goto all)
goto menu


:clean
cd rom
rmdir /s /q extractedRom\
md extractedRom
goto menu

:extract
cd tools
echo extracting...
7za x -o"../rom/extractedRom" "../rom/*.zip" 1>>nul
goto menu

:hebrew
cd rom/extractedRom/system
rmdir /s /q fonts\
md fonts
cd C:\Users\Lior\Hero\ROMS\Myn\Tools
xcopy /y /s fonts "c:/users/lior/hero/roms/myn/Rom Manager/rom/extractedRom/system/fonts"
goto menu

:apps
cd rom/extractedRom/system/app
del com.htc.StockWidget.apk
del com.htc.TwitterWidget.apk
del com.htc.WeatherWidget.apk
del Flickr.apk
del htcbookmarkwidget.apk
del HtcTwitter.apk
del Maps.apk
del Stk.apk
del teeter.apk
goto menu

:prop
cd rom/extractedRom/system
build.prop
goto menu

:zip
msg * gsd
cd tools
7za a -tzip "C:\Users\Lior\Hero\ROMS\Myn\Rom Manager\rom\zippedrom" "C:\Users\Lior\Hero\ROMS\Myn\Rom Manager\rom\extractedRom\*"
cd sign
call sign
goto menu



at the beginning, the lines that suppose to show time and date and --------- does not work, with no errors.
even if i add line like
echo ----------------------------

in the :menu



thanksQuote
@echo off

if (%1)==(0) goto skipme
echo -------------------------------------------------------------------------- >>logerror.txt
echo ^|%date% -- %time%^| >>logerror.txt
echo -------------------------------------------------------------------------- >>logerror.txt
script 0 2>> logerror.txt
:skipme

Quote
at the beginning, the lines that suppose to show time and date and --------- does not work, with no errors

This thread looks very familiar. Feel like I got on a merry-go-round on Groundhog Day and can't get off.

Actually, the lines at the beginning are NOT coded to show you the date and time as you are redirecting the echo output to a file. In fact, the echo statements work exactly as you coded them. If you want the date and time displayed on the console, lose the redirection. If you want both redirection and console output you'll need to code both outputs. I already posted in your other thread that you cannot send the same output to two different streams in the same instruction.

Just guessing, but is your batch file named script? If so the reference to script in the file is a RECURSIVE transfer of control BACK to the running file. Not only can this create problems, it is not best practice. What are you trying to do? Your file has a check for the first COMMAND line parameter which skips over the redirection. Why?

How did you manage to turn something so simple into a Rube Goldberg contraption?

I know what you said, but i asked the creator of the script that we were talking about and he told me to add this lines.
and it worked.
in addition, this function redirected the echo time and date to the log file and also to the console.
but now it is not working(echo time and date).i realy dont know what are you talking about.Quote from: Lwe on March 30, 2011, 08:36:02 AM
but now it is not working(echo time and date).

The error message is : 'script' is not recognized as an internal or external command,
operable program or batch file
.

How do you know it doesn't work? It never runs. Use a fully qualified path to script and use the call instruction if script is a batch file.

If you had explained from the beginning what script is and what it does, you wouldn't have needed two threads and countless posts for a simple question.




8725.

Solve : Reading Data From A Text File Using DOS Batch?

Answer»

I have a list of filenames in a simple .dat FILE:

POS123
POS145
POS787

For each of these rows of data I want to TRY and find the NAMED file in the file system and copy the file to a specific directory.

I have tried using the FOR command together with an IF EXIST statement but it appears to read the name of the file only as when i use TYPE >> filename I get the entire list, although I only want the ones I cna find

Is this possible ?You need to post the code you have written so far.


8726.

Solve : Pull Metadata through Command Line?

Answer»

Hello,
Is there any way to pull or set Metadata from a command line? Something like attrib, but for metadata and not attributes. I've been looking online for a while and still no luck; any ideas?

An example would be if you wanted to find all files with a certain author or artist, or audio files of 320kbps, or anything else about those files you would be interested in reading (instead of having to have that information in the file name).

Thanks!

-Steve

The command line is a poor database MANAGER. Some in formation is only EMBEDDED i n the file data and not the files TRIBUTES as seen by the Operating SYSTEM. The OS does not define such data types. The OS has a limited ability to get information about some special files types. And often this is not visible at the command line, but only in Windows Explorer.

Try using the library system of i Tunes or Win amp or even Windows Media Player. Such re media library programs will find the additional data that is not visible to then operating system.

yes you can, through the power of vbscript (or powershell.)

8727.

Solve : Starting a directx game from batch?

Answer»

When I start a directx GAME from a batch LIKE this:
START "test" /WAIT game.exe
then the game APPARENTLY takes on the "environment" of the batch file, ie it will not have hardware acceleration available, like it has when STARTING game.exe from windows.
So how do I start that game in its own process?

Just curious...
Why would you have a need to launch a game from batch ? ?The game has problems with directdraw. So in the batch I first turn off ddraw, then start the game, wait for the game to close, re-enable ddraw and exit.Forget it, the problem lies with how I turned off ddraw. Thread solved.

8728.

Solve : finishing a hard-drive recovery process?

Answer»

Greetings All!
Brand new member here. Please forgive etiquette errors while I get used to this forum. I'll be as brief as I can laying out my problem.

YES, I KNEW BETTER than to not back up my hard drive, so please don't blast me for not overcoming my ADD with disciplined backup. Of course, hints for backup will be welcome after I get everything running.

I have a Toshiba A65 using XP.

So I sent my dead internal hard drive to a lab for recovery. They had to rebuild the heads &/or bearings twice to get to the data but they indicated a 99.99% recovery. They sent my original hard drive back in working order (for how long I don't know) and a new hard drive with the old one "cloned" onto it, but not guaranteed to boot. It didn't boot. I tried directly accessing the new drive (in an external housing) from another computer. I seems to be a near-perfect copy of my original drive, but I can't access anything under my user name presumably because of my original boot-up password.

I put my original drive in the laptop and it booted and "seems" perfect, but I know it is running on borrowed time. I removed the boot password for now. I decided to copy as much as possible onto my Passport drive starting with "My Documents". This was working until it choked on paths that were too long. Breaking down the file structure so it will copy and then rebuilding it will take unreasonable time. I know I need to operate the drive as little as possible to have the best chances of getting everything so I am unsure how to proceed.

I decided that if I can get a good copy of my original hard drive somewhere I'll try using the Toshiba restore disk to make the new hard drive bootable while preserving the rest of the cloned image. The people at the recovery lab suspected hidden Toshiba files did not make the transfer &/or their uniqueness on the original drive made them unusable on the new drive. Still, I have the concern that the restore disk might not work or might proceed into a format process beyond my control.

I've read about the XCOPY command. I think it might work but my research leaves me with 2 questions. The lesser question is "assuming adequate space, will XCOPY copy the entire drive, structure intact, to a named folder on my passport drive?" The other issue relates to the long-path-name issue. During my info-search I saw a lot of comments about XCOPY choking on long file and path names.

I hope I've made my problem clear without excess verbage. If you can advise me how to proceed I would appreciate it. If this is so complex it needs a live conversation and you are such a wonderful and generous person that you would talk me through, email me or post your email address and I'll send you my phone number.

Thanks in advance to everyone who reads this.

Sincerely,
install4you in north-central Alabama I may be wrong, but possibly the difficulty in accessing the cloned data on the new drive might be down to OWNERSHIP issues? Have you tried taking ownership? Was it an NTFS volume?


Please forgive my ignorance, but how do I take ownership? I'm not sure about NTFS. My problem would still remain in wanting a secure total backup before attempting to restore bootability on the new hard drive.

Is there a utility that can copy a whole drive with its structure intact into a named folder an another drive? ...even if the folders in folders in folders (etc.) create long path names?

Thankshttp://support.microsoft.com/kb/308421Thanks. That looks doable. I'll reinstall the drive in the external housing and give that a try as soon as I can. I'll report back what works.

That still leaves me with the copy problem. I won't try to make the new hard drive bootable until I know I have a full copy of everything on a reliable drive.Use Robocopy not xcopy. It can handle network interruptions, retains file attributes and timestamps, and it can copy file and folder names exceeding 256 characters.Quote from: Uselesscamper on August 28, 2011, 05:13:06 PM

Use Robocopy not xcopy.

As I understand it, Robocopy is not available in XP. Am I missing something?Robocopy, or "Robust File Copy", is a command-line directory replication command. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was introduced as a standard feature of Windows Vista, Windows 7 and Windows Server 2008.
You can download and install Windows Resource Kit to XP.
http://www.microsoft.com/download/en/details.aspx?id=17657
Quote from: Uselesscamper on August 28, 2011, 06:59:54 PM
You can download and install Windows Resource Kit to XP.

The link you posted specifies that one system requirement is Windows Server 2003 family. What I have is stand-alone XP Home. Should that still work?Yes it will work on XP. I kind of mentioned that in the previous post. Quote from: Salmon Trout on August 27, 2011, 12:42:24 PM
... Have you tried taking ownership? ...

I followed the link provided and it was helpful. I followed the steps to take ownership of the entire folder under my user ID (previously inaccessible). After the computer spent a long time making the changes I was able to fully access everything including My Documents. So I set out to copy everything to another drive for back-up. I decided to copy the smaller folders first and then I could walk away while larger items were copying.

Here's where BIG TROUBLE started. As I COPIED files & folders (drag/drop) I encountered the same kind of or similar "access denied" messages as before, this time with files & folders previously & still readable. "Naturally" I took ownership of those items so I could copy them. I think it while taking ownership of a "Windows" folder when the ENTIRE DIRECTORY STRUCTURE WAS CORRUPTED! This was, of course, before I copied any of My Documents.

This reinforces the truism "a little knowledge is a dangerous thing!"

Fortunately, my original drive is running. I've been backing it up but it is a slow process. I know I have My Documents and everything else is gravy.

I'm planning to finish backing up and then do a full restore from the Toshiba CD on the new drive I bought from the recovery lab. The most tedious part of that will be the 5 years of Microsoft updates and service packs that will have to be installed on the new drive. Yes I know I should buy a new computer but after paying for the hard-drive recovery I can't do that right now. I have my original software disks to reload. I'll pull IE favorites from the original drive or a backup. And etc....

ANY SUGGESTIONS to ease the Microsoft updates issue?

Thanks in advance for any assistance!Of course, a user does not have the facilities to do what a Technician would do....having said that.

I would slave that little HD off of my desktop PC, with appropriate adapters and access it with my own OS.
That's also a good time to scan it for Viruses, Trojans and Spyware.

Then I would access all the desired files and copy them to my own HD, from where I could burn them to CD's or DVD's for a PERMANENT record. I regularly do this for my customers.

Now as for that Toshiba recovery CD..... it's an exact copy of the hard drive as it was when it came out of the Toshiba factory.
If you run it, everything on your drive will be gone and the PC will be just like new again.
I'd use that only on the new drive and NOT on the old one that has all your data on it.
The only one of those recovery CD's that I've ever used, was actually made with "Ghost", my favorite backup program.

Good Luck,

Oooops! Double post!
Quote from: TheShadow on September 05, 2011, 12:03:09 PM
Of course, a user does not have the facilities to do what a Technician would do....having said that.

I'm fortunate that the recovery lab was so busy they didn't take the parts back out of my old drive per their normal process. So far it is running great, although I know that's just the drive trying to lull me into a false sense of security. I'm convinced that inanimate objects grow brains and work consciously against us. If I back up well it will run forever. If not it will fail as soon as it uniquely holds my most critical files. I've been copying everything from it to my WD Passport drive.

When I'm confident I have sufficient backup, I'll store the old drive in a fire safe and run the Toshiba disk on the new drive. I was under the impression that there were some options with its use. I had hoped to back up the new drive and then try to restore the boot function only. Oh well...no matter...I'll let the restore disk do a total job on the new drive and then start the rest of the rebuild.Quote from: install4you on August 27, 2011, 01:44:49 PM
Please forgive my ignorance, but how do I take ownership? I'm not sure about NTFS. My problem would still remain in wanting a secure total backup before attempting to restore bootability on the new hard drive.

Is there a utility that can copy a whole drive with its structure intact into a named folder an another drive? ...even if the folders in folders in folders (etc.) create long path names?

Thanks
I highly recommend TODO backup.
it can copy your whole drive or specific file. Besides COPING, it can do schedule backup set, incremental backup, differential backup. Differential/Incremental backup and automatic backup.


http://www.todo-backup.com/products/home/free-backup-software.htm
8729.

Solve : Variables within variables?

Answer»

I am trying to develop a script that will turn the jumbled up mess of files I have in a folder into an organized folder with a set naming scheme. There are a lot of files, so doing this manually would take almost an entire two days of work, plus I'd really like to see if this can be done in batch anyway. The problem is coming from one line in the for command...

Code: [Select]@echo off
setlocal enabledelayedexpansion
cls

cd "C:\Users\User\desktop\Stuff\testbat"

for /f "delims=" %%F in ('dir /s /b *Form4*') do (
set OldName=%%~nF

echo !OldName!
set /p NameStart=Offset by ?
set /p NameLength=Characters Long?

set NewName=!OldName:~!NameStart!,!NameLength!!%%xF

echo !NewName!>>Namelog.txt
)

The error comes in on the set NewName line. I have tried using quotes around the two embedded variables, and I get the following in the txt file

OldName:~"7","11"%xF
OldName:~"0","13"%xF

I tried using the single quotes around the two variables and GOT the same only with single quotes around the numbers. I tried using double quotes around the entire string and got this

"Form4 Example1NameStartNameLength"%xF
"Example2 Form4NameStartNameLength"%xF

I even tried quotes on the inside of the exclamation points (i.e. !"OldName:~!NameStart!,!NameLength!"!%%xF) and I got this in the file

~7,11"%xF
~0,13"%xF

I even went so far as to try to export the Name inputs to other files and then try importing the data into the correct places (got rid of extra exclamation points, but cmd prompt kept erroring saying it could not find file specified, even though I hardcoded the file paths). Nothing seems to work.

Does anyone know how to get this to work? Or if it is even possible?You can do it, but you have to double up some of the exclamation marks/percent signs. I am about to leave for work but later today I shall post a WORKED out example.
Call Set might work in this instance. Try:

Code: [Select] call set NewName=%%OldName:~!NameStart!,!NameLength!%%%%~xF
Good luckQuote from: Dusty on September 16, 2011, 12:15:45 AM

Call Set might work in this instance.

Good suggestion
The call set worked great. Thank you. One more question, more in line with the for command. How do you "skip" within a for command? Example: I want the user to see what is being renamed and asked if they want to continue with the renaming process, if they do not, how do I skip that particular file, but keep the for command running. I've tried using labels and goto within the do, but they don't seem to work.Quote from: Raven19528 on September 16, 2011, 09:08:31 AM
How do you "skip" within a for command?

Ask for a user input e.g. y or n and then use an IF test, remembering to use delayed expansion.


@echo off
setlocal enabledelayedexpansion
cls
cd "c:\Users\User\desktop\Stuff\testbat"
for /f "delims=" %%F in ('dir /s /b *Form4*') do (
set OldName=%%~nF
echo Old file name : !OldName!
set /p NameStart="Offset from start ? "
set /p NameLength="Characters Long ? "
call set NewName=%%OldName:~!NameStart!,!NameLength!%%%%~xF
echo New file name : !NewName!
set /p DoRename="Rename [y/n] ? "
if /i "!DoRename!"=="y" (
echo Adding !NewName! to Namelog.txt
echo !NewName! >>Namelog.txt
) else (
echo Skipped
)
echo.
)


Quote from: Salmon Trout on September 16, 2011, 10:57:36 AM
Ask for a user input e.g. y or n and then use an IF test, remembering to use delayed expansion.


set /p DoRename="Rename [y/n] ? "
if /i "!DoRename!"=="y" (
echo Adding !NewName! to Namelog.txt
echo !NewName! >>Namelog.txt
) else (
echo Skipped
)



Explanation of above:

set /p DoRename="Rename [y/n] ? "

Ask if user wants to rename. Request y or n as input.

if /i "!DoRename!"=="y"

IF test. The /i switch makes it case insensitive, so that the test will be satisfied if the user types y or Y. Anything else at all will cause the test to be unsatisfied, for example YES, Yes, yes etc.

As with FOR, you can have a single line IF test such as:

if /i "!DoRename!"=="y" echo !NewName! >>Namelog.txt

or you can use parentheses to make multi line structures like this

if /i "!DoRename!"=="y" (
echo Writing to file!
echo !NewName! >>Namelog.txt
echo Finished writing to file
)


If you want to do one thing or things if the IF test is satisfied, and another thing or things if it is not, you can use ELSE like this:

if /i "!DoRename!"=="y" (
echo Writing to file!
echo !NewName! >>Namelog.txt
echo Finished writing to file
) else (
echo skipping file
echo !NewName! >>Skipped-Namelog.txt
)


Note that for ELSE to work, you need a closing parenthesis ")" and ELSE and an opening parenthesis "(" all on the same line as you see above.

Note also that whether in a loop or not, you MUST match opening and closing parentheses carefully!

Also note that you can do simple IF - ELSE stuff like this

if /i "!DoRename!"=="y" (echo You typed Y) else (echo You did not type Y)

A final point is that when you do an echo to a file like this it is a good habit to have a space before the > or >> redirection operators.

echo %something% >>file.txt

This is because if you don't you will get problems if the final character of %something% is a figure. This is to do with redirection of console streams.



I found a way of doing this without going through a lot of embedded if statements:

for /f "delims=" %%F in ('dir /s /b %tarstr%') do call :renamesubroutine %%F

This gets all of the files with the *tarstr* target string in the folder and passes them to the rename subroutine that holds all of the looping and error-checking that I want to have in my program. I will post it either here or in the Batch programs thread.Alright, so this is a lot, and I still haven't added my error-checking/correction coding into it at all, but it has the functionality that I am looking for. Thank you for all of the help with this one.

Code: [Select]@echo off
setlocal enabledelayedexpansion
title Renamer v1.1
mode con: cols=61 lines=15
set origdir=%~dp0
set numnam=0

call :targets
cls
call :startstring
cls
call :endstring
cls

:renaming
for /f "delims=" %%F in ('dir /s /b %tarstr%') do (
cls
set OldFilePathAndName=%%~dpnxF
set OldName=%%~nF
set OldFilePath=%%~pF
set Extension=%%~xF
set FileDate=%%~tF
echo !OldName!!Extension! in !OldFilePath!
echo.
set /p Continue=Edit this filename {y,n}
if /i "!Continue!"=="y" call :EditNameSubroutine

set NewName=!startstr!!NewName!!endstr!!Extension!

cls
echo.
echo !NewName!
echo.
echo Is this correct
set /p yn9={y,n}
if /i "!yn9!"=="y" (
echo !NewName! from !OldName!!Extension! >>%origdir%\Renamelog.txt
ren "!OldFilePathAndName!" "!NewName!"
set /a numnam=!numnam!+1
)
)

cls
echo You changed the name of !numnam! files
echo You can view the names that were changed
echo in the Renamelog.txt file located at
echo %origdir%
echo.
echo Thank you for using Renamer v1.1
echo.
ping 1.1.1.1 -n 1 -w 10000>nul
goto eof


:targets
:loop
cls
echo Is the directory path in the targetdirectory.txt file?
set /p yn1={y,n}
cls

if /i "%yn1%"=="y" (
set /p tardir=<targetdirectory.txt
) else (
echo Type full path of target directory
set /p tardir=
)
if exist %tardir% (
cd %tardir%
) else (
echo Target does not exist
echo Please try again
ping 1.1.1.1 -n:1 -w:3000>nul
goto loop
)

echo Is there a target string you want to enter?
set /p yn2={y,n}
if /i "%yn2%"=="y" (
echo.
echo Type target string for renaming
set /p tarstr=[Target]
set tarstr="*!tarstr!*"
goto addtarstrques
) else (
set tarstr=*
goto eof
)

:addstring
cls
set /p addstr=[Target]
set addstr="*%addstr%*"
set tarstr=%addstr% %tarstr%
echo Searching for strings: %tarstr%
:addtarstrques
cls
echo.
echo Is there an additional string you wish to look for?
set /p yn3={y,n}
if /i "%yn3%"=="y" goto addstring
goto eof


:startstring
:startloop
cls
echo Is there a standard starting string
echo to the naming convention?
set /p yn4={y,n}
if /i "%yn4%"=="y" (
cls
echo Enter standard start string
echo [Include an ending space if desired]
echo.
set /p startstr=
) else (
set startstr=
goto eof
)
echo The current start string is "%startstr%"
echo Is this okay?
set /p yn5={y,n}
if /i "%yn5%"=="n" (
set startstr=
goto startloop
)
goto eof


:endstring
cls
echo Is there a standard ending string to the naming convention?
set /p yn5={y,n}
if /i "%yn5%"=="n" (
set endstr=
goto eof
)
cls
echo Would you like the end string to
echo include the date the file was created
set /p DateEnd=[y,n]
cls
if /i "%DateEnd%"=="y" call :DateEndFormatting
cls
echo Would you like the end string to include
echo today's date
set /p yn6={y,n}
cls
echo Enter standard end string
echo [Include spaces if desired]
set /p origendstr=
if /i "%yn6%"=="y" call :DateTodayFormatting
if "%DateEnd%"=="y" set origendstr=%origendstr%[date created]
echo The current end string is "%origendstr%"
echo Is this okay?
set /p yn7={y,n}
if /i "%yn7%"=="n" (
set origendstr=
goto endstring
)
if /i "%DateEnd%"=="y" set origendstr=%origendstr:~0,-14%
goto eof


:DateEndFormatting
echo In what format would you like the
echo date to appear:
echo.
echo 1. dd Mmm yy
echo.
echo 2. yyyymmdd
echo.
echo 3. Mmm dd, yyyy
echo.
echo 4. mm/dd/yy
echo.
echo 5. More...
echo.
set /p DateEndForm=Selection {1-5}-
if "%DateEndForm%"=="5" goto more
goto dateendskip
:more
cls
echo 6. dd Mmm yyyy
echo.
echo 7. yy/mm/dd
echo.
echo 8. mm/dd/yyyy
echo.
echo 9. yymmdd
echo.
set /p DateEndForm=Selection {6-9}-
:dateendskip
goto eof


:DateTodayFormatting
echo In what format would you like the
echo date to appear:
echo.
echo 1. dd Mmm yy
echo.
echo 2. yyyymmdd
echo.
echo 3. Mmm dd, yyyy
echo.
echo 4. mm/dd/yy
echo.
echo 5. More...
echo.
set /p DateTodayForm=Selection {1-5}-
if "%DateTodayForm%"=="5" goto more
goto settodayform
:more
cls
echo 6. dd Mmm yyyy
echo.
echo 7. yy/mm/dd
echo.
echo 8. mm/dd/yyyy
echo.
echo 9. yymmdd
echo.
set /p DateTodayForm=Selection {6-9}-
:settodayform
if "%date:~4,2%"=="01" set todaymonth=Jan
if "%date:~4,2%"=="02" set todaymonth=Feb
if "%date:~4,2%"=="03" set todaymonth=Mar
if "%date:~4,2%"=="04" set todaymonth=Apr
if "%date:~4,2%"=="05" set todaymonth=May
if "%date:~4,2%"=="06" set todaymonth=Jun
if "%date:~4,2%"=="07" set todaymonth=Jul
if "%date:~4,2%"=="08" set todaymonth=Aug
if "%date:~4,2%"=="09" set todaymonth=Sep
if "%date:~4,2%"=="10" set todaymonth=Oct
if "%date:~4,2%"=="11" set todaymonth=Nov
if "%date:~4,2%"=="12" set todaymonth=Dec
if "%DateTodayForm%"=="1" set origendstr=%origendstr%%date:~7,2% %todaymonth% %date:~12%
if "%DateTodayForm%"=="2" set origendstr=%origendstr%%date:~10%%date:~4,2%%date:~7,2%
if "%DateTodayForm%"=="3" set origendstr=%origendstr%%todaymonth% %date:~7,2%, %date:~10%
if "%DateTodayForm%"=="4" set origendstr=%origendstr%%date:~4,6%%date:~12%
if "%DateTodayForm%"=="6" set origendstr=%origendstr%%date:~7,2% %todaymonth% %date:~10%
if "%DateTodayForm%"=="7" set origendstr=%origendstr%%date:~12%/%date:~4,5%
if "%DateTodayForm%"=="8" set origendstr=%origendstr%%date:~4%
if "%DateTodayForm%"=="9" set origendstr=%origendstr%%date:~12,2%%date:~4,2%%date:~7,2%
goto eof


:DateEndSet
if "!FileDate:~0,2!"=="01" set month=Jan
if "!FileDate:~0,2!"=="02" set month=Feb
if "!FileDate:~0,2!"=="03" set month=Mar
if "!FileDate:~0,2!"=="04" set month=Apr
if "!FileDate:~0,2!"=="05" set month=May
if "!FileDate:~0,2!"=="06" set month=Jun
if "!FileDate:~0,2!"=="07" set month=Jul
if "!FileDate:~0,2!"=="08" set month=Aug
if "!FileDate:~0,2!"=="09" set month=Sep
if "!FileDate:~0,2!"=="10" set month=Oct
if "!FileDate:~0,2!"=="11" set month=Nov
if "!FileDate:~0,2!"=="12" set month=Dec
if "%DateEndForm%"=="1" set endstr=%origendstr%!FileDate:~3,2! !month! !FileDate:~8,2!
if "%DateEndForm%"=="2" set endstr=%origendstr%!FileDate:~6,4!!FileDate:~0,2!!FileDate:~3,2!
if "%DateEndForm%"=="3" set endstr=%origendstr%!month! !FileDate:~3,2!, !FileDate:~6,2!
if "%DateEndForm%"=="4" set endstr=%origendstr%!FileDate:~0,6!!FileDate:~8,2!
if "%DateEndForm%"=="6" set endstr=%origendstr%!FileDate:~3,2! !month! !FileDate:~6,2!
if "%DateEndForm%"=="7" set endstr=%origendstr%!FileDate:~8,2!!FileDate:~0,5!
if "%DateEndForm%"=="8" set endstr=%origendstr%!FileDate:~0,10!
if "%DateEndForm%"=="9" set endstr=%origendstr%!FileDate:~8,2!!FileDate:~0,2!!FileDate:~3,2!
goto eof


:setcaps
set NewName=!NewName:A=a!
set NewName=!NewName:B=b!
set NewName=!NewName:C=c!
set NewName=!NewName:D=d!
set NewName=!NewName:E=e!
set NewName=!NewName:F=f!
set NewName=!NewName:G=g!
set NewName=!NewName:H=h!
set NewName=!NewName:I=i!
set NewName=!NewName:J=j!
set NewName=!NewName:K=k!
set NewName=!NewName:L=l!
set NewName=!NewName:M=m!
set NewName=!NewName:N=n!
set NewName=!NewName:O=o!
set NewName=!NewName:P=p!
set NewName=!NewName:Q=q!
set NewName=!NewName:R=r!
set NewName=!NewName:S=s!
set NewName=!NewName:T=t!
set NewName=!NewName:U=u!
set NewName=!NewName:V=v!
set NewName=!NewName:W=w!
set NewName=!NewName:X=x!
set NewName=!NewName:Y=y!
set NewName=!NewName:Z=z!
:caps
cls
echo !NewName!
echo.
set /p caps=How many capital letters?
if "!caps!"=="0" goto eof
for /l %%i in (1,1,!caps!) do (
cls
echo Capital Letter %%i
echo !NewName!
echo 012345678911111111112222222222333333333344444444445555555555
echo 01234567890123456789012345678901234567890123456789
set /p capoff=At Position-
set /a endcap=!capoff!+1
call set before=%%NewName:~0,!capoff!%%
call set capletter=%%NewName:~!capoff!,1%%
call set after=%%NewName:~!endcap!%%

set capletter=!capletter:a=A!
set capletter=!capletter:b=B!
set capletter=!capletter:c=C!
set capletter=!capletter:d=D!
set capletter=!capletter:e=E!
set capletter=!capletter:f=F!
set capletter=!capletter:g=G!
set capletter=!capletter:h=H!
set capletter=!capletter:i=I!
set capletter=!capletter:j=J!
set capletter=!capletter:k=K!
set capletter=!capletter:l=L!
set capletter=!capletter:m=M!
set capletter=!capletter:n=N!
set capletter=!capletter:o=O!
set capletter=!capletter:p=P!
set capletter=!capletter:q=Q!
set capletter=!capletter:r=R!
set capletter=!capletter:s=S!
set capletter=!capletter:t=T!
set capletter=!capletter:u=U!
set capletter=!capletter:v=V!
set capletter=!capletter:w=W!
set capletter=!capletter:x=X!
set capletter=!capletter:y=Y!
set capletter=!capletter:z=Z!

set NewName=!before!!capletter!!after!
)
cls
echo !NewName!
echo.
echo Are there any additional caps needed?
set /p yn14={y,n}
if /i "%yn14%"=="y" goto caps
goto eof


:EditNameSubroutine
:editname
cls
echo !OldName!
echo 012345678911111111112222222222333333333344444444445555555555
echo 01234567890123456789012345678901234567890123456789
echo.
set /p NameStart=Enter Start Position-
set /p NameEnd=Enter End Position-
set /a NameLength=1+!NameEnd!-!NameStart!

if /i "%DateEnd%"=="y" call :DateEndSet else set endstr=%origendstr%

call set NewName=%%OldName:~!NameStart!,!NameLength!%%

cls
echo !NewName!
echo Would you like to make changes to this part
echo {Start and end strings will be added later}
echo.
set /p yn10={y,n}
if /i "!yn10!"=="y" (
call :setcaps

cls
echo !NewName!
echo.
echo Would you like to insert anything into the name
set /p yn8={y,n}
if /i "!yn8!"=="y" call :insertsubroutine

cls
echo !NewName!
echo.
echo Would you like to remove anything from the name
set /p yn12={y,n}
if /i "!yn12!"=="y" call :removesubroutine
)
cls
echo !NewName!
echo.
echo Do you need to make any other changes?
echo.
set /p yn15={y,n}
if "%yn15%"=="y" goto editname
goto eof


:insertsubroutine
:insertsub
cls
echo !NewName!
echo 012345678911111111112222222222333333333344444444445555555555
echo 01234567890123456789012345678901234567890123456789
echo To the **right** of what position would
echo you like to insert the string?
set /p strpos=Right of Position-
echo What would you like to insert
set /p stradd=[String]
call set NewName=%%NewName:~0,!strpos!%%!stradd!%%NewName:~!strpos!%%
cls
echo !NewName!
echo.
echo Is there anything else that needs to be added
set /p yn11={y,n}
if /i "!yn11!"=="y" goto insertsub
goto eof


:removesubroutine
:removesub
cls
echo !NewName!
echo 012345678911111111112222222222333333333344444444445555555555
echo 01234567890123456789012345678901234567890123456789
echo What are the start and end positions
echo of the string to be removed?
echo.
echo Note that the start position should be
echo the last character that you want to stay
echo and the end position the last character
echo you want deleted
echo.
set /p remstpos=Start Position-
set /p remenpos=End Position-
call set NewName=%%NewName:~0,!remstpos!%%%%NewName:~!remenpos!%%
cls
echo !NewName!
echo.
echo Do you need to remove anything else
set /p yn13={y,n}
if /i "!yn13!"=="y" goto removesub
8730.

Solve : Replace String Using SET Command?

Answer»

Hello,
I need to replace a STRING in a variable with another string. The second or replacing string is also in a variable.
I USE the SET command to do the string replacement and I can't figure out how to replace a string with a variable.

For example:
set a=Hello kitty
set b=doggy

To change "Hello kitty" to "Hello doggy" with a literal:
set a=%a:kitty=doggy%
Result is: Hello doggy

To replace the string with a variable, I tried the following and failed:
set a=%a:kitty=%b%
The result is: Hello b

The % in front of the variable b is causing the problem. Can anyone give me some suggestions on fixing my problem?

Thank you.set a=%a:Kitty=%%b%%Thank you for your reply.

That seemed to work but when I tried to manipulate the first string like echo or concatenate, the word doggy is repeated again.

set a=%a:kitty=%%b%%

Echo %a%
set a=%a%again
Echo %a%

Result is:
Hello doggy (this CAME from the first set command)
Hello doggydoggy (this came from the first Echo command)
Hello doggydoggyagain (this came from the second Echo command)

Any suggestions?Oops. Your suggestion works. I had too many set commands in my script so it appeared that the word doggy was repeated. Sorry.

Thank you very much for your help.That's GOOD!

8731.

Solve : how to know a particular process is running or not using ms dos?

Answer»

hi

i want to create a batch file such that if internet EXPLORER is running then close mozilla firefox...

here how can i handle using IF


pls explain


thank you
sir
You don't use an if. One technique is to get a list of all running processes and then determine if iexplore.exe is among them. If it is, then kill firefox.

Code: [Select]@echo off
tasklist | find /i "iexplore.exe" && taskkill /im firefox.exe

Good luck.

thanks for reply

but above command is running in dos but through notepad it is not running..

SHOWING error tasklist is not a INTERNAL external or BATCHFILE comand.

pls tell
thanksQuote from: amittripathi on September 16, 2011, 12:55:05 AM

but above command is running in dos but through notepad it is not running..

Please explain. It's probably too early for this stuff, but how do you run a PROGRAM through notepad?

Not all machines have tasklist installed so try to replace it with tlist:

Code: [Select]@echo off
tlist | find /i "iexplore.exe" && taskkill /im firefox.exe

If an error still occurs, you can download tasklist from here and use the original code posted.

Good luck.
8732.

Solve : What is WRONG??

Answer» QUOTE from: BC_Programmer on September 15, 2011, 05:55:25 PM
isn't something that I am apt to consider.

Hmmm... I believe they have a WORD for this as WELL...
8733.

Solve : Copying, moving and renaming of files?

Answer» Scenario:
I have a folder called box that contains a number of folders with names A, B, C… These folders contain varying number of files with a serialized naming scheme Zxx, where, x represents a number (0, 1, 2…).

Action:
I would like to have a batch file that performs the following:
  • CREATE a destination folder whose name is given to a placeholder at the same place as box.
  • Accesses the folders in box alphabetically
  • Copies their files into the destination folder with a serialized naming scheme of type Zxx with a possibility of getting to Zxxx.


This is a little difficult to start on because I am not quite certain what it is you are trying to do. Can you show an example of what you are looking for?

From what I am reading, I think what you are trying to do is this:

TRANSFER File named "Z00" in folder "A" under folder "box"
...
to
...
File named "Z000" in folder "Destination"

Please let us know if this is indeed what you are trying to do or if it is something different.There is another similar topic to this one in which Salmon Trout and CN-DOS replied with some code that does almost what you are trying to do here.

Quote from: Salmon Trout on August 24, 2011, 01:56:50 PM
Your convention of having 2 dots was what I did not know about... try this. For guidance there are many sites and one of the best is ss64.com

Code: [Select]@echo off
setlocal enabledelayedexpansion

For /f "delims=" %%F in ('dir /s /b *.pdf') do (
set OldPathAndName=%%~dpnxF
Set OldName=%%~nxF

Set NewName=!OldName!

set NewName=!NewName:And=and!
set NewName=!NewName:The=the!
set NewName=!NewName:Is=is!
set NewName=!NewName:Not=not!

echo Ren "!OldPathAndName!" "!Newname!"
)

Quote from: CN-DOS on August 31, 2011, 05:53:17 AM
Code: [Select]@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /s /b *.pdf') do (
set NewName=%%~na
set NewName=!NewName:And=and!
set NewName=!NewName:The=the!
set NewName=!NewName:Is=is!
set NewName=!NewName:Not=not!
ren "%%a" "!Newname!.pdf"
)

These pieces of code are meant to rename the files and change the names to have lowercase "and"s, "the"s, "is"s, and "not"s, but uses the same principles (and commands) that you would WANT to use for a program like this. The code that I am writing is going to copy the files to the destination folder and rename them with a Zxxx format, but the first x will be the folder they were originally from. So Z00 in folder A will become ZA00 in the new location.

The coding that I am using uses some stuff that is going to require some work on your part. I am going to assume for this code that the "box" folder you are referencing is located on the desktop of "User" and the "destination" folder is in the same location. This is important because you will notice the :~ that is used in the code to parse out the file name. You are going to have to do the research to find out exactly how many characters there are in the fully qualified path name.

Here is a short explanation of what you'll see. To parse out a variable, you use the ':~' to designate that you only want part of the variable. The first number will be the number of characters there are before the start of the parsing, and the second number is the number of characters to use in the parsing.
Example:
%date% will expand to Wed 09/14/2011
%date:~4,2% will expand to 09
Utilizing one number "N" will utilize the remainder of the variable after 'n' characters
%date:~10% will expand to 2011

With that, here is a rough go at what you are trying to do with the limited knowledge I have on the FOR command:

Code: [Select]@echo off
setlocal enabledelayedexpansion

set NewFilePath=C:\Users\User\desktop\destination {your full path of destination folder}

for /f "delims=" %%F in ('dir /s /b /o:n') do (
set OldFilePath=%%dpF
set OldName=%%~nxF
set OldFilePathAndName=%%dpnxF
set Folder=!OldFilePath:~26,1! {Here's where you need to do your research}

set NewName=!OldName:~0,1!!Folder!!OldName:~1!

copy !OldFilePathAndName! !NewFilePath!

ren !NewFilePath!\!OldName! !NewName!
)
Side note on the :~

You can utilize the - to utilize a from the end type of selection. So a !OldFilePath:~-2,1! Will take the second to last character in the path name (the last character always being a \). Or if you know you want to utilize only a certain part of the path that starts 12 characters in and you don't want the last slash in there, you can set up !OldFilePath:~11,-1! Or use it however you need to. I missed a couple of ~s in the original code.

Corrected.

Code: [Select]@echo off
setlocal enabledelayedexpansion

set NewFilePath=C:\Users\User\desktop\destination {your full path of destination folder}

for /f "delims=" %%F in ('dir /s /b /o:n') do (
set OldFilePath=%%~dpF
set OldName=%%~nxF
set OldFilePathAndName=%%~dpnxF
set Folder=!OldFilePath:~26,1! {Here's where you need to do your research}

set NewName=!OldName:~0,1!!Folder!!OldName:~1!

copy !OldFilePathAndName! !NewFilePath!

ren !NewFilePath!\!OldName! !NewName!
)
This is what I mean:

Transfer file named "z00" in folder "A" under folder "box"
...
to
...
File named "z00" in folder "Destination"

Continue the above procedure till the last file in “A” is transferred and renamed into “Destination”

Transfer file named "z00" in folder "B" under folder "box"
...
to
...
File named "zxx" in folder "Destination”, where "xx" is a serial increment of the last file named in folder "Destination". Example, if the last file transferred to "Destination" was named "z56", then, the first file transferred to "Destination" from "B" is named "z57".
This continues until the last file in the last folder of “box” has been transferred to "Destination".
Note:
The folders in “box” are accessed in alphabetical order.
Only the last two characters of the file names change and this may change to three characters.
The folder “Destination” is named by the user via place holder and is located on the same path as “box”.

I am going through the script you posted will post the outcome later. Thanks for ss64.com it helps.
This becomes a two step process then. The first step moves the file into a temporary location so as not to rename the wrong file or copy the wrong file at any point. The second step is to ensure that the proper naming convention is used. A simple if command will ALLOW for the naming convention to be correct. Please say something if there are parts of the script that you don't understand.

Code: [Select]@echo off
setlocal enabledelayedexpansion

:setnewpath
set /p NewFilePath=Please enter the full path of the destination folder
cls
if exist %NewFilePath% goto continue
echo That location is not valid. Please type a valid location for the destination.
echo The path needs to exist currently, so please make the folder if it does not already exist.
goto setnewpath

:continue
set TempFilePath="c:\users\user\desktop\Temp"
set number=0

for /f "delims=" %%F in ('dir /s /b /o:n') do (
set OldName=%%~nxF
set Extension=%%~xF
set OldFilePathAndName=%%~dpnxF
if /i !number! leq 9 (
set NewName=z00!number!!Extension!
) else (
if /i !number! leq 99 (
set NewName=z0!number!!Extension!
) else (
set NewName=z!number!!Extension!
)
)

copy !OldFilePathAndName! !TempFilePath!

ren !TempFilePath!\!OldName! !NewName!

copy !TempFilePath!\!NewName! !NewFilePath!
del !TempFilePath!\!NewName! /q

set /a number=!number!+1
)
rd c:\users\user\desktop\Temp /q
Over thinking computer tasks always leads to complexities. Try to keep it simple.

Code: [Select]@echo off
setlocal enabledelayedexpansion

set seq=0
set source=c:\temp\box
set /p target=Enter Destination Folder:

md %target%

for /f "tokens=* delims=" %%i in ('dir %source% /a:-d /s /b') do (
set leadzero=000!seq!
set leadzero=!leadzero:~-3!
copy %%i %target%\Z!leadzero!%%~xi
set /a seq+=1
)

You will be prompted for a fully qualified destination directory. The source directory (box) is hardcoded but feel free to change it.

Good luck.

8734.

Solve : Using batch files for temporary user access to the local admin group?

Answer»

Users on my office network need to run an application/command (eg: regsvr32 -u "c:\PROGRAM Files\Outlook Add-in\ShinseiOutlookCom.dll") that requires local admin rights. For security purposes, we prefer not to provide users with local admin rights. Would you recommend trying to write a BATCH file to add each user to the local admin group when he or she clicks the program's desktop? This privilege level would only last until the user exits the program...Any body can suggest me on this?

Thanks,

BijuQuote from: Biju007 on September 13, 2011, 09:46:59 PM

Would you recommend trying to write a batch file to add each user to the local admin group when he or she clicks the program's desktop? This privilege level would only last until the user exits the program...Any body can suggest me on this?

The problem you run into if you use batch is that in order to write it, it would have to have a hardcoded USERNAME and password. There are some ways to use backdoor options to make it very difficult for the user to obtain the password, but in most cases, when using batch, it is very difficult to make it impossible. The work around that we have used to a great deal of success in my working environment is a batch file that merely starts another batch file located on a network drive as a SPECIFIED user. That user is the only user with access to the .txt file that contains the administrative name and password, and then the file imports those items into the program to run. It's a big end-around process and it would be a lot easier if the network allowed us to run other software other than batch files, but we have what we have and that's how we have worked it. If you would like, I can give you a sample of the two batch files. My SUGGESTION though would be to go with some other programming medium that would alow you to hardcode the username and password but not allow it to be readily available to the user.It is great idea which you offered to me, Thanks for that. I came to know in a batch file we can call VB script in-order to secure the administrative name and password. But right now; if you can share the sample batch files as you told I can try to implement as my requirement.

Looking forward from you.

Biju B.Batch 1

Code: [Select]net use z: /delete /y
net use z: \\networklocation /USER:[emailprotected] -password /persistent:no

start z:\batch2.bat /username=joe.schmo /password=password

Batch 2

Code: [Select]@echo off
net use b: /delete /y
net use b: \\anothernetworklocation /persistent:no
set /p adminuser=<b:\adminuser.txt
set /p adminpass=<b:\adminpass.txt
net use b: /delete /y

start c:\localprogram.exe /username=%adminuser% /password=%adminpass%

Let me know if you run into any issues.
8735.

Solve : Need help writing a batch file that copies and overwrites files repeatedly?

Answer»

I'm working on writing a batch FILE for where I work that will help automate some things that have to be done manually.

I work for a retail company that does its credit sales over a network, but when there is a network outage there is a dial-up backup system that can take over and run their credit over dial up.
But this requires the store manager to go on the server and run a few commands through the command LINE - and the obstacles in GETTING them to do this are a real support issue.

I've got the monitoring working, it's copying these files around that is giving me problems.



So here's what I have
credit_working - the currently active file that gives instruction to the credit server
credit_IP - a file stored somewhere else that has instructions for credit running normally over the network
credit_DIAL - a file stored somewhere else that has instructions for credit running over the dial-up modem

- the batch file monitors for a network outage
- when the network goes down
* credit_dial needs to be copied over credit_working

- when the network comes back up
* credit_ip needs to be copied over credit_working
- it goes back to monitoring



The problem I'm having is -
When it goes to copy credit_ip over credit_working, it gives the error message "the system cannot find the file specified"



What can cause this? All the files are do exist and are never being deleted, only overwritten.
I've tried taking the long way around and deleting credit_working, copying credit_ip over, and then renaming it - but it gave the same response.
Any suggestions?
I'll put the affected part of the script in my next post.Here is the part I'm having trouble with.
There's a lot more to it than this, and I'm changing the names and directories for clarity.
I'll put GENERAL STATEMENTS in parenthesis, so assume that all works ok.
Remember, the file credit_working is the one that's actually being used by the credit server.



(The batch file runs all the time and checks for a network connection)
(It has lost connection and goes to :DOWN)

:DOWN
copy "C:\credit_dial.xml" "C:\credit_working"


(goes to monitoring for a connection again)




(After the connection comes back up, it comes to :RESTORED)

:RESTORED
copy "C:\credit_IP.xml" "C:\credit_working"


(goes back to monitoring for a network outage)






It is during :RESTORED that it gives the error message "the system cannot find the file specified"
Any suggestions?Maybe you changed directories. Is the script running with sufficient permissions? I suspect you may need to post a bit more of your code.

8736.

Solve : change dos font size in native dos, not windows shelled dos?

Answer»

I remember way back being able to make dos font size larger, on an old 8088 running DOS 5.0, Thought it was part of the SET command, but cant seem to locate it. Digging online I found a statement that to me just sounds way incorrect... Quote

"MS-DOS uses characters built into the video card. Thus, you cannot "change" the font."
Doesn't the OS parameters/drivers control size and font type of text that is displayed and the video card is just displaying what it is told to display on its x,y grid?

http://wiki.answers.com/Q/How_do_you_change_font_size_in_DOS_command

Changing font/text size is simple in windows shell PROPERTIES, but ran across this the other day with DOS displaying on my 27" CRT TV in which the text is too small to barely make out, and I am using HTPC with DOS 6.22 boot floppy to play old games. Wolfenstein 3D really likes the XMS and EMS memory which is obsolete in modern windows. If it were just WOLF3D that I was playing, I'd just add that exe to autoexec.bat on the floppy, but I also play other games so it would be nice to avoid the eye strain by increasing the font size, which I PRETTY much just sit back and type as correct as possible to start the game, and if I fumble a key try again with the text blur of a 27" CRT TV..lol

I suppose at some point I should modernize from 1995 TV technology and go with a nice flat screen which would be crisp text even if small... but until I have a couple hundred bucks with nothing better to do, I'd liek to make the dos text larger in DOS 6.22..lolOK. Yes, you can change the font size. You are talking about DOS 6.22 running native, not inside of anything or under anythig.

It depemds on the vbideo card. DOS does not have a font sests like nWindows has. The fonts are crated by a generator in the video card. Most of the nolder video cards had no wayn to alter the font used. But it was posible to change the number of chars on a line. And the number of lines on the display.

It is hard to get this information now. Just about every reference is about using DOS under windfows, whichn is nnot really DOS.
This is nabout the MODE command. It can change the ndisplay.
http://www.csulb.edu/~murdock/mode.html

(I am running Vista and FF 6 and no SPELL checker.)mode co40Thanks guys... "I forgot all about MODE.com" and that would be why i was not finding my answer through google when looking to do it using SET . Looked into the Mode co40 and COLOR with 40 characters per line should definitely do the trick on bootable DOS 6.22 floppy disk adding that to config.sys line.

I just need to make sure that I add MODE.com to it for that to work, since the floppy was created using format a:/s a long time ago ( 1995-ish ), and I bet its not on that disk.!!! These days people say who still uses floppies... well I do for native old school gaming and bios flashes!

I've been hanging around Windows too long and these bits of info are disappearing from what I probably knew 20 years ago before Windows spoiled me... lol

Today with Windows you can alter your font just by command shell window properties. And for quite a few years I have used that feature when needing to make text bigger in command shell... so the sector for making text bigger in my brain got overwritten with that tidbit vs the old way pre-windows. Will tag that piece of info with ATTRIB +R this time to protect it from getting lost again..lol
Quote from: DaveLembke on September 13, 2011, 01:40:53 AM
adding that to config.sys line.
won't work there. it's a command. add it to autoexec.bat.
Quote
These days people say who still uses floppies...

I do. Well, actually, that's not true, because nearly all my floppies are bad. I do have a floppy drive installed though.
Quote from: DaveLembke on September 13, 2011, 01:40:53 AM
These days people say who still uses floppies

I do too. They have all of my StarCraft custom maps on them, from when I used to stay up until ridiculous hours drinking Wal-Mart brand soda and eating Cheetos while creating works of art in StarCraft map editor. Ow! Flashbacks of "triggers" PROGRAMMING... painful...

I thought MODE.com was a standard load after DOS 6. Maybe it was another one. I can't remember back that far very well.Quote from: Raven19528 on September 13, 2011, 09:36:14 AM
I do too. They have all of my StarCraft custom maps on them, from when I used to stay up until ridiculous hours drinking Wal-Mart brand soda and eating Cheetos while creating works of art in StarCraft map editor. Ow! Flashbacks of "triggers" programming... painful...

I thought MODE.com was a standard load after DOS 6. Maybe it was another one. I can't remember back that far very well.

MODE was in all version of DOS, at least since 3.11, most likely earlier. It's never been on the boot disks created with sys or format /s, though.Thanks BC for the correction ... I too was thinking autoexec.bat, but the site I was on was talking about it in config.sys, so thats why I was like well maybe because its a configuration parameter where services and memory allocation parameters are set. Tonight hopefully I'll get to test out MODE co40.
8737.

Solve : Timer program?

Answer»

I recall way back that it was possible to write a program that could control lights etc. from an old computer.The output was via the parallel port to enable solid state RELAYS. Does anyone know of a commercially available version?

Art They wrote BOOKS on that. You cn do a Google search:
parallel port projects
will get near 3 million hits.
Top ITEMS:
http://logix4u.net/Legacy_Ports/Parallel_Port/A_tutorial_on_Parallel_port_Interfacing.html
http://www.edaboard.com/thread155813.html
http://www.lvr.com/parport.htm

This one is a GOOD reference with external links
http://ee.cleversoul.com/parallel-port.html

8738.

Solve : lil help?

Answer»

Hi im new at BATCH files and im stuck i read up and everything but it still wont work heres my script so far...


echo off
echo v1.2
color 1e
echo . .
echo . RaNdOm FACTS .
echo . .
echo Hello welcome to Random Facts
echo press A-Z to continue to facts or X to exit
echo have fun
if %option%==a goto a
if %option%==b goto b
:a hello
:b hi
pause


any ideas?? please

p.s its saying right fast then close that "goto is unsuspected at this time".:loop
set /p option=Your choice A -Z (X to exit)
if "%option%"=="a" goto a
if "%option%"=="b" goto b
if "%option%"=="x" exit
echo Wrong input!
goto loop
:a
echo hello
:b
echo hi



Better...

:loop
set /p option=Your choice A -Z (X to exit)
if "%option%"=="a" goto a
if "%option%"=="b" goto b
if "%option%"=="x" goto end
echo Wrong input!
goto loop

:a
echo hello
goto end
:b
echo hi
goto end

:z
echo last label
:end




Like Salmon Trout is showing, what seems to be missing from your code is the ability to input the 'option' variable. Without "set"ting the variable, it will not register that the variable even EXISTS and you run into the error you are seeing. The /p flag tells the script that it is waiting for user input for the variable, which is why you can put text after the = and it will show in the program rather than setting the variable to equal that.

Example:

set /p option=Your choice A -Z (X to exit)

willl generate this in the program:

Your choice A -Z (X to exit) |

where the | would be the cursor for the user to type at and the 'option' variable would equal their input.
If however you typed the following into the code:

set option=Your choice A-Z (X to exit)

the option variable would equal "Your" and the rest of the line would be dismissed and there would be no option for the user to input anything. Batch is very finnicky so a lot of things are learned through trial and error, and of course picking other people's brains.

8739.

Solve : Replace String with Wildcards using DOS Batch file!?

Answer»

Quote from: graymj on August 24, 2010, 05:47:50 AM

Show some effort!!!! You have no idea what your are talking about! I have spent over 6 weeks reading books and researching several sites! I work on it around the clock! attempting to use the example below! I just don't post all my efforts here! I would have over 20 pages of crap!
sidewinder has shown you how to do it with batch, although not to your requirement. But i am expecting you follow his guidance on that piece of snippet and work on it. That's the effort i am talking about. I am not expecting you to post all your already done scripts here. So i am saying, are you really waiting for him to solve your own (project/homework) problem?

Quote
If you decide not to help! Then do so Keep your replies silents! I don't need any negitive responces! Thank you!
we are not here to do your work/project for you. As you already saw, I have helped you a lot. I have shown you ways you could do it with ease, and others have shown you native ways to do it with batch and vbscript. BUT the problem is caused by you yourself. Only DOS is allowed ? Typical project/school homework restriction , isn't it ?

If the DOS you mentioned is really the MSDOS 6.22 , it most probably can't be done in a pure DOS, except you have to use some extra tools. If it can be done, it would probably be obscure and arcane. Either way, you are on my blacklist of people not to help from now on.
I must have misinterpreted your original post about the numerics after the PT to be deleted too. In any case, that created a real problem when trying to create a batch file to do just that. Seems those special characters in the data file cause the NT interpreter to choke.

By the way, the VBScript I posted only removed the PT not the following numerics. This little ditty fixes that problem:

Code: [Select]Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")
Set objRE = CreateObject("VBScript.RegExp")
objRE.Global = True
objRE.IgnoreCase = False

Set inFile = fso.OpenTextFile("d:\wfc\sniplib\WSH-RegEx-putSearchReplace.txt", ForReading)
Set outFile = fso.OpenTextFile("c:\temp\Regex.chg", ForWriting, True)

Do Until inFile.AtEndOfStream
strLine = inFile.ReadLine
objRE.Pattern = "^GOTO\s(.*?)\bPT\s{2}[0-9]{1,}\b"
Set colMatches = objRE.Execute(strLine)
If colMatches.Count > 0 Then
' objRE.Pattern = "PT\s{2}" 'remove PT leave remaining digit(s)
objRE.Pattern = "PT\s{2}[0-9]{1,}\b" 'remove PT and remaining digit(s)
strLine = objRE.Replace(strLine, "")
End If
outFile.WriteLine strLine
Loop

Considering you have Win7 and all those tools available, I would have thought a batch solution would be your last choice.

Good luck. Thank You Sidewinder! I got your vb to work as well! Yes there was issues
understanding my orginal request! I read everything I could find on the subject! But there seem to be no way to do this in DOS! Learn alot from U
and your example! Thank many time more!
Sorry ghostdog74 you feel that way! And as Sidewinder has come to undrstand that my orginal requirements were missunderstoud! Which I attempted to point out with several examples! I want no one to do my work! I had a programming issue and tried to throw it out here to help myself and others LEARNING batch programming on DOS, which I'm more
than sure this solution will! I'm well versed in Pearl & writing UNIX Scripts,
both would only require one liners to solve this issue! But there was a company standard for whatever reason to only use DOS! which I'm attempting to do! Best Wishes and Thanks for your help in the pass as well!
Quote from: graymj on August 24, 2010, 08:56:41 AM
I'm well versed in Pearl

Pearl?

For some reason I suspect you meant:

Perl

That would be correct! Thanks for the correction! I hate unfinished business, so I came up with this monstrosity. I apologize if it looks something like Curly the Neanderthal would mark on the cave wall. I gotta learn to stop over thinking things.

Code: [Select]@echo off
setlocal enabledelayedexpansion
if exist c:\temp\regex.chg del c:\temp\regex.chg

for /f "tokens=* delims=" %%f in (c:\temp\regex.txt) do (
set strLine=%%f
set subLine=!strLine:~0,4!
if /i .!subLine! EQU .GOTO call :getLoc
echo !strLine! >> c:\temp\regex.chg
)
goto :eof

:getLoc
for /l %%i in (0, 1, 67) do (
call set strChunk=%%strLine:~%%i,2%%
if .!strChunk! EQU .PT call set strLine=%%strLine:~0,%%i%% & goto :eof

)
goto :eof

Change the file paths as appropriate. If the position of PT changes you MAY need to change the 67 value in the for /l statement to increase the search range.

Good luck. WOW! HA HA! How did you come of with this? I can't WAIT to try it!

the logic seem wild! I'm trying to break it down now! THANKSSSSSSSSSSS!HI Sidewinder It Works Great! Just having a few problems intergrateing into my code! but thats a small problem! also developeing a method to
Identify which column the PT start and pass that value to your routine!
You're the BEST! THANKS AGAIN & AGAIN!There is no need to send the starting position of PT to the routine. The whole point was to make the code generic. The code found PT in the data file you posted at offset 64 in all the records that contained it.

The :getLoc routine processes records that have GOTO in the first four bytes. By starting at offset 0 (record position 1), it increases the record position by 1, reading 2 byte chunks of the record until PT is found or offset 67 is reached, WHICHEVER comes first. The 67 was arbitrary. Once the offset of PT is found (stored in the %%i token), the code uses truncation to eliminate the high order bytes. The logic is fairly simple, it was the batch notation that was challenging.

The FOR /L %variable IN (start,step,end) DO statement uses the "end" parameter as the indicator when to stop the loop. In this case it represents the highest offset to check before quitting the loop. You can EXCEED the record length without the code throwing an error. Ensure the "end" parameter is large enough to include the entire record without being so large as to needlessly waste CPU cycles.

The code can probably be tweaked for more efficiency. For instance, the search for PT could start at offset 4; we already know offsets 0-3 contains GOTO

Hope this helps. Thanks! I was busy changeing the 67 thinking it was a start position! but after checking out other sites realized it was like an range! Your explanation was great! This is avery useful piece of code! Thx Again for the info!Is there a way to modify the VBS code example (posted by Sidewinder - thanks by the way) to replace the expression found, ie, find /.*$ (evrything from the slash to enf of line) and replace it with a blank? I am new to vbs, and am not sure what the syntax is to substitute something for the found expression -

In advance, thanks!Scratch my previous post, I did not see the ealier post from Sidewinder with an example of exactly what I needed (once again, thanks very much!). I modified it slightly for what I needed (below), and it works beautufully.
Thanks Sidewinder!!

Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")
Set objRE = CreateObject("VBScript.RegExp")
objRE.Global = True
objRE.IgnoreCase = True

Set inFile = fso.OpenTextFile("c:\temp\test3.txt", ForReading)
Set outFile = fso.OpenTextFile("c:\temp\test33.txt", ForWriting, True)

Do Until inFile.AtEndOfStream
strLine = inFile.ReadLine
objRE.Pattern = "=/.[^/]*"
Set colMatches = objRE.Execute(strLine)
If colMatches.Count > 0 Then
objRE.Pattern = "=/.[^/]*" 'remove everyting from = up to but not including next /, replace with =
strLine = objRE.Replace(strLine, "=")
End If
outFile.WriteLine strLine
LoopTo replace all occurrences of one string in a file by another string, there is even a simpler solution:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=* delims=" %%f in (%1) do (
set strLine=%%f
set strLine=!strLine:= !
:: tab^ ^space
echo !strLine! >> %1
)Update:

1) The output file, of course should be #2 :-(
2) Only exclamation marks, the text between two exclamation marks, and empty lines that are lost. All the other known problem characters (both outside and inside of "..." and "%...%") are retained.
8740.

Solve : Copying files from a corrupted drive using "xcopy" from the Command Prompt?

Answer»

Hello... I originally posted this in the Windows 7 forum, but I think it's more of an MS DOS issue, and hopefully someone here can help...

I was running a freeware defrag program when the process halted (prob. due to loss of power/sleep mode) and my laptop no longer boots from the hard drive when powered on. Win7 startup repair does not restore the system. Using the Command Prompt I can still SEE my files, but there are no 'autoexec.bat', 'config.sys' or 'command.exe' files on the ROOT (and I'm not 100% sure that Win 7 even uses them). I think I may have to reformat and reinstall to my factory original disks, which will reformat my hard drive and destroy months of data.

Before I do that, I want to try to save the "my documents" files to an external drive, then reload them after the rebuild. I intend to use the 'xcopy' function from the Command Prompt to copy the entire c:\ drive to the external drive, then when my machine is rebuilt, copy all of my documents back.

I plan on using the "xcopy c:\*.* /a /e /k" command from inside the root directory of the external drive.

Will this work, and does anyone have any other advice for me to try before I reformat my drive?

My laptop is a Toshiba Satellite 505 - s6005, and I'm running Win 7 Home and Office 64bit.

Thank you for any help you can give...
Tom
Seaview1231. The most conservative recovery method is to GET another HDD for that laptop and install Windows. The make the old HDD a USB device using an adapter.

2. Alternative to this is to use a Desktop PC to backup the original drive as a slave drive, using another TYPE of adapter, if needed.

3. Another approach is to boot a Linux distro from a USB device and see if you can locate important files and burn them to a DVD.

4. Or, thaxter are some third party Windows tools that do what you would do with the Linux USB device. CHECK this:
http://www.ubcd4win.com/howto.htm

Otherwise, trying to recovery files using a corrupt system is often futile. And may even be destructive.
And that is not just IMHO.

8741.

Solve : Calling a JDK command?

Answer»

I have a question about using a command from the JDK. I PLAN to distrubite the BATCH FILE to clients, will they NEED to have the specific JDK command file in the FOLDER or will the batch file work without them having the JDK?depends what program ("command") it is you are running from the JDK.

8742.

Solve : Looping and Zipping of folders?

Answer»

Hi All,

I am new to Dos Batch. My problem now is that I need to loop through a directory with many subfolders. I need to zip those subfolders (using 7ZIP) and place the zipped subfolders into another directory.

Before zipping
My main root is C:\Users\ayaka\Desktop\ZipTask\TestingDirectory
Sample FOLDERS:
C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\April2001\temp123\temp123.html
C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\April2001\temp234\temp234.html
C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\May2001\temp345\temp345.html
C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\May2001\temp456\temp456.html

After zipping
C:\Users\ayaka\Desktop\ZipTask\TestDir

The folders should be zip according to the month and year. So, there should be 2 zipped folders, mainly April2001 and May2001 in C:\Users\ayaka\Desktop\ZipTask\TestDir

I had done ABIT of coding, but it doesn't really work.

Here's the code:

Code: [Select]@ECHO off


FOR /R C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\ %%G IN (*) DO (


for /F "tokens=1-7 delims=\ " %%i in ("%%G") do (
Set folder=%%o
Set path=%%i\%%j\%%k\%%l\%%m\%%n\%%o

cd C:\Users\ayaka\Desktop\ZipTask\7za920

7za.exe a -t7z %path%\%folder%.7z C:\Users\ayaka\Desktop\ZipTask\TestDir


)

)
@ECHO on

Can anyone help me? Thanks.I managed to create the batch file to do it. But I have no idea why the program stopped after the first zipped folder is made.

Here's the new code:

Code: [Select]@ECHO off
FOR /R C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\ %%G IN (*) DO (
FOR /f "tokens=1-7 delims=\ " %%i in ('dir /b /s "%%G"') do (

IF NOT EXIST C:\Users\ayaka\Desktop\ZipTask\TestDir\%%o.7z (

echo %%i\%%j\%%k\%%l\%%m\%%n\%%o

cd C:\Users\ayaka\Desktop\ZipTask\7za920

7za.exe a -t7z C:\Users\ayaka\Desktop\ZipTask\TestDir\%%o.7z C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\%%o
)
)
)
@ECHO on

Output:
C:\Users\ayaka\Desktop\ZipTask\TestDir\April2004.7z

The output should also include this file, but the program did not continue:
C:\Users\ayaka\Desktop\ZipTask\TestDir\May2004.7zFinally, I made it. But it will take a very long time if there are alot of folders in each folder and many files in each folder.

Here's the code:

Code: [Select]@echo off

echo.going to execute loop
call:loop
echo.returned from loop
echo.&pause&goto:eof

:loop
FOR /R C:\Users\ayaka\Desktop\ZipTask\TestDir\ %%G IN (*) DO (
echo.going to execute cont
call:cont %%G
echo.returned from cont
)
echo.going back to loop
echo.&pause&goto:eof

:cont
FOR /f "tokens=1-7 delims=\ " %%i in ('dir /b /s "%~1"') do (
echo %%i\%%j\%%k\%%l\%%m\%%n\%%o &GT;> path.txt
IF NOT EXIST C:\Users\ayaka\Desktop\ZipTask\testingFolder\%%o.7z (
cd C:\Users\ayaka\Desktop\ZipTask\7za920
7za.exe a -t7z C:\Users\ayaka\Desktop\ZipTask\testingFolder\%%o.7z C:\Users\ayaka\Desktop\ZipTask\TestingDirectory\%%o
)
)
goto:eof

Anybody has any idea on how to improve this? So that it can be done efficiently?

8743.

Solve : Find Replace filename batch?

Answer» QUOTE from: Salmon Trout on September 08, 2011, 12:55:03 PM
Are the people who own the network your employers?

Yes.Quote
It really blows my mind, how far afield batch programming has gotten in the past few years.
It seems like many jobs would be better done in a MUCH higher programming language.

When I started writing batch files back in the DOS 2.0 days, THINGS were certainly a lot simpler.
And if I couldn't write a batch file to do SOMETHING, I just did it manually.

I agree. It seems like batch used to be a very simple and concise language, but then they started adding on more and more s*** and now it seems like it has pretty much no regular structure and an awkward SYNTAX.
8744.

Solve : Search file and edit it?

Answer»

1. Test.vdf (before)

Code: [Select]{
{
Section 1
}
{
Section 2
}
{
Section 3
}
{
Section 4
}
}

2. Script

Code: [Select]@echo off
setlocal enabledelayedexpansion
for /f "delims==" %%A in ('dir /b /s S:\*.vdf') do (
set filepath=%%~dpA
set filename=%%~nA
set fileExtn=%%~XA
)
Echo Found file
Echo Path %filepath%
Echo Name %filename%%fileExtn%
cd /d "%filepath%"
set linecount=0
for /f "delims=" %%A in ('type "%filename%%fileExtn%"') do set /a linecount+=1
if exist "%filename%-new%fileExtn%" del "%filename%-new%fileExtn%"
set linenumber=0
for /f "delims=" %%A in ('type "%filename%%fileExtn%"') do (
set /a linenumber+=1
if !linenumber! equ %linecount% (

echo { >> "%filename%-new%fileExtn%"
echo Section 5 >> "%filename%-new%fileExtn%"
echo } >> "%filename%-new%fileExtn%"
echo } >> "%filename%-new%fileExtn%"

) else (
echo %%A >> "%filename%-new%fileExtn%"
)
)
echo Rename
echo ren "%filename%%fileExtn%" "%filename%-OLD%fileExtn%"
ren "%filename%%fileExtn%" "%filename%-old%fileExtn%"
echo ren "%filename%-new%fileExtn%" "%filename%%fileExtn%"
ren "%filename%-new%fileExtn%" "%filename%%fileExtn%"
echo done

1. Test.vdf (after)

Code: [Select]{
{
Section 1
}
{
Section 2
}
{
Section 3
}
{
Section 4
}
{
Section 5
}
}

8745.

Solve : Script runs in CMD window but not from .bat file?

Answer»

I have this string that I use to read a directory of files and then process them according to the second part of the string.

WORKS fine when i directly enter it into a CMD window, but when writing it into a .bat file, the CMD flashes and goes AWAY WITHOUT processing the files. The directory may contain up to 4000 files and what I am trying to do is loop through each file in the directory and insert the data into a Database. And as I said, works fine when I manually PASTE it into a CMD window, but when running from .bat file, doesn't work.

Here is the string.. any suggestions?

for /f %A IN ('dir /b C:\scripts\files\work\out\*.txt') do call LOAD AR01 -file "C:\scripts\files\work\out\%A" -addAt command prompt FOR variables have one percent sign: %A

In a batch script they have two percent signs: %%A


8746.

Solve : Copy / Xcopy?

Answer»

Sorry for all the old questions but it has been awhile since I have been in the DOS thing that I have forgotten everything. What is the difference between copy and xcopy? Can I delete a whole directory with one of those?http://www.google.com/search?hl=en&rlz=1B3MOZA_en-GBUS386US388&q=difference+between+copy+and+xcopy&aq=f&aqi=g3g-m1&aql=&oq=&gs_rfai=xcopy is for directories and files. copy will only move files from one location to another. You cannot delete using xcopy or copy. If you want to delete, use del and if you want to remove a directory use rmdir.8)HOW DO I TRANSFER ALL FILES FROM ONE HARD DRIVE TO ANOTHER SO I CAME BOOT FROM THAT DRIVE
IN XP PROBoomer960 - Welcome to the CH forums.

Please don't hijack another member's thread, start one of your own.

To achieve what you want you have to clone the drive using dedicated software. I use XXClone (a free restricted version is available) and there are other packages available on the WWW.

Good luckAfter read and re-reading my post I am trying to remember What was I THINKING? I know that you can not delete in copy or xcopy, I was asking about moving files. Thanks for the help."Move" is nothing more than Copy + Delete, without verification.
It's actually sort of a dangerous command, as I found out, years ago, when I was working just in DOS.

The list of switches for XCOPY is EXTENSIVE and allows the command to do a lot of work, with a lot of selectivity.

I use it daily to back up all my data files, that are new or have just been changed, to like folders in my Backup hard drive.
That totally precludes me loosing any of my data in case my main drive goes up in a big ball of fire and smoke.
Don't laugh.....that CAN happen.

Cheers!
I'm not sure if you are working in a post XP environment or not, but there is also the functionality of robocopy. It has the ability to selectively include or selectively exclude files and directories, it allows you to mirror attributes, or only copy certain attributes, to change certain flags on files, and a lot of other tricks. I believe they only introduced it in the Vista command prompt and later, but if you are in that environment, it's definitely worth checking out. Just try a robocopy /? |more in your cmd line and take a look at all the goodies available (including log filing, in case you want to set up a routine backup with logging capability.) I personally have a backup that runs robocopy daily, with a logging function that names the log file the current date so I don't get confused when something was first backed up. Oh, and thats the other cool thing about robocopy, when you are using it in a backup style capacity, is it will automatically skip files that are already in the new location (can be toggled) so you don't have to worry about the time it takes to copy an entire directory, it will only copy new (or newer VERSIONS of) files. It also has a /mov switch if you are wanting to delete the source after the copy (as you suggested originally), and /purge or /mir switches to make the destination look just like the source.

8747.

Solve : Auto unrar?

Answer»

Hi guys.
I found this script on another forum and it works like a charm.

Code: [Select]@REM ------- BEGIN demo.cmd ----------------
@setlocal
@echo off
set PATH="C:\Program Files\WinRAR\";%path%
for /F %%i in ('dir /s/b *.rar') do call :do_extract "%%i"
GOTO :eof

:do_extract
echo %1
mkdir %~1.extracted
pushd %~1.extracted
unrar e %1
popd

REM ------- END demo.cmd ------------------
There's only one problem. Somethimes the .rar FILE is named
file_name.part1.rar
file_name.part2.rar
file_name.part3.rar
and so on
. So if it is 24 parts it means that the file/movie or what ever will be unpacked 24 times
I've tried to search the web for an answer but cant find anything.One way would be to process the rar file or files in 2 stages:

1. The rar files which do not have ".part" in the name.

2. The rar files whose name ENDS with ".part1.rar".

By the way, I fixed a few THINGS in that script... it handles files with spaces in the names now.

Code: [Select]@setlocal
@echo off
set path="C:\Program Files\WinRAR\";%path%
for /F "delims=" %%i in ('dir /s/b *.rar ^| find /v ".part"') do call :do_extract "%%i"
for /F "delims=" %%i in ('dir /s/b *.part1.rar') do call :do_extract "%%i"
goto end

:do_extract
echo %1
mkdir "%~1.extracted"
pushd "%~1.extracted"
echo unrar "%1"
unrar e "%~dpnx1"
popd
goto :eof

:end

sorry, accidentally clicked "quote"
Sweet. I'll test it asap.
Thanks for the help

8748.

Solve : How to give xml file name as input?

Answer» HELLO Folks,


Need help to pick right dos command.

I have a requirement to create a Batch file 'Y', that runs a batch file 'X'

The batch file 'X' has command that calls a program BUILD in java, when batch file 'X' is EXECUTED it ask to input name of a an .XML file.

can you please help with command to give .xml file name as input to dos

Thanks,
Syed




Generally the set command is used to prompt for input in a batch file:

Code: [Select]SET /P variable=[promptString]

Example:
Code: [Select]set /p xml=Enter XML file name:

The prompt Enter XML file name: will APPEAR on the console and wait for user input. When the user enters a response, the value entered will be available in the %xml% variable.

Quote
The batch file 'X' has command that calls a program build in java, when batch file 'X' is executed it ask to input name of a an .XML file.

This is ambiguous. Does the batch file request the input file name or does the Java program?

Good luck. Thanks For the response. Its actually Java Program needs input file
8749.

Solve : Bat to test existence of a file on list of computers and copy new file.?

Answer»

Hi All

I would appreciate some HELP with this batch file.

I'm trying to write a bat file to ...

1. Interrogate several computers, listed in a .txt file (currently only contains 3 hosts for test purposes)
2. Check for the instance of a specific file (indicating the installation of a specific application)
3. If the file doesn't exist, comment to that effect.
4. If the file does exist, overwrite it with an amended file (without user response).
5. Send the results of the bat file operations to a separate log file.

The code I'm using is ...

Code: [Select]FOR /F %%a IN (C:\FraserDATA\BATs\LispProblems\ComputerList.txt) do (
IF EXIST "c$\Program Files\AutoCAD Architecture 2010\Support\acad2010doc.lsp" GOTO COPY_FILE
echo File doesn't exist
echo.
echo \\%%a ##################
echo.
) >>C:\FraserDATA\BATs\LispProblems\FileCopied.txt
:COPY_FILE
COPY C:\FraserDATA\BATs\LispProblems\acad2010doc.lsp "\\%%a\c$\Program Files\AutoCAD Architecture 2010\Support\" /y

pause

The only result I'm getting is "File doesn't exist" for each computer entry (one definitely has the requiste folder/file entry).

ANYONES help or GUIDANCE would be very much appreciated.
Quote

Interrogate several computers, listed in a .txt file (currently only contains 3 hosts for test purposes)

We don't do that here.Quote
We don't do that here.

Not sure what is meant by this comment. I am administering a NETWORK of some 400+ computers, some with CAD installed. Several have been infected with a mild worm that has corrupted a .lsp file. I wanted to interrogate each computer, check for the existence of the program and replace the corrupt file.

I thought that this was a forum where I would be able to find some sensible help regarding a few problems I have in in writing a batch file to that effect.

Apologies for my ignorance.
You generate a computer name in the %%a variable but then fail to use it in existence test.

Try it this way:

Code: [Select]IF EXIST "\\%%a\c$\Program Files\AutoCAD Architecture 2010\Support\acad2010doc.lsp" GOTO COPY_FILE

On another level, the logic seems illogical. If the lsp file exists, the logic goes to copy_file, drops into the pause, then exits the code. Try either moving the copy_file logic into the for statement and using a if/else construct, or, use a call instead of a goto, and use goto :eof statements after the for loop and after the the copy statement.

Why the pause statement? The output is redirected to a log file, so you shouldn't need it. Batch file are best run from the COMMAND prompt.

8750.

Solve : exit batch if copy fails?

Answer»

Hi, can anyone help me modify this batch file to exit if it fails to complete the 'copy' job

the main function of the batch file is to copy a test file from a source to a destination
and count the time it takes to complete the copy

sometimes the destination computer is turned off so the comand WINDOW displays '0 files copied' in stead of '1 file copied'

i need to add an 'if' satement so that the batch will jump to :end if the file fails to copy

@echo off

FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Second /FORMAT:table ^| findstr /r "."') DO (
set Milisecond=%time:~9,2%
set Day=%%A
set Hour=%%B
set Minute=%%C
set Second=%%D
)
set /a Start=%Day%*8640000+%Hour%*360000+%Minute%*6000+%Second%*100+%Milisecond%

copy c:\temp\1meg.test \\COMPUTERX\c$\temp
::::::: i need to jump from this point to the :end if this copy job fails to complete ::::::::

echo COMPUTER: ADL017 >> c:\temp\BENCHMARK\TIMER.log
echo DATE: %DATE% >> c:\temp\BENCHMARK\TIMER.log
echo tIME: %TIME% >> c:\temp\BENCHMARK\TIMER.log

FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Second /Format:table ^| findstr /r "."') DO (
set Day=%%A
set Hour=%%B
set Minute=%%C
set Second=%%D
)
set Milisecond=%time:~9,2%
set /a End=%Day%*8640000+%Hour%*360000+%Minute%*6000+%Second%*100+%Milisecond%
set /a Diff=%End%-%Start%
set /a DiffMS=%Diff%%%100
set /a Diff=(%Diff%-%DiffMS%)/100
set /a DiffSec=%Diff%%%60
set /a Diff=(%Diff%-%Diff%%%60)/60
set /a DiffMin=%Diff%%%60
set /a Diff=(%Diff%-%Diff%%%60)/60
set /a DiffHrs=%Diff%

:: format with leading zeroes
if %DiffMS% LSS 10 set DiffMS=0%DiffMS!%
if %DiffSec% LSS 10 set DiffMS=0%DiffSec%
if %DiffMin% LSS 10 set DiffMS=0%DiffMin%
if %DiffHrs% LSS 10 set DiffMS=0%DiffHrs%

echo COUNTER: %DiffHrs%:%DiffMin%:%DiffSec%.%DiffMS% >> c:\temp\BENCHMARK\TIMER.log

echo **************************************** >> c:\temp\BENCHMARK\Timer.LOG

:end Code: [Select]copy c:\temp\1meg.test \\COMPUTERX\c$\temp || goto endThe way I understand it is that you what the bat file to copy a file and log how long it takes. And for the bat file to end if it can't FIND it.
I don't know why you have all the set statements. Here's ONE that worked for me.
@echo off
echo Starting on %date% at %time%>>c:\users\bonz\bat\TIMER.log
if not exist \\COMPUTERX\c$\temp\*.* goto NOTTHERE

copy c:\temp\1meg.test \\COMPUTERX\c$\temp
echo 1meg.test has been copied to \\COMPUTERX\c$\temp >>c:\users\bonz\bat\TIMER.log
echo Done copying at %time%>>c:\users\bonz\bat\TIMER.log
goto end

:NOTTHERE
echo Couldn't find \\COMPUTERX\c$\temp>>c:\users\bonz\bat\TIMER.log
echo ending at %time%>>c:\users\bonz\bat\TIMER.log

:end
echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>>c:\users\bonz\bat\TIMER.log

This is what printed to the TIMER.log file.

Starting on Sat 04/02/2011 at 23:28:39.74
Couldn't find \\COMPUTERX\c$\temp
ending at 23:29:00.95
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As you can see, it also gave me the message that it couldn't find the destination as well as the starting date & time and ending time. I noticed it took some time trying to find \\COMPUTERX\c$\temp. I counted off 21 seconds and that's what it shows in the TIMER.log file. (actually 21.21 seconds)