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.

251.

Solve : close windows on error with batch file?

Answer»

Hi
I have written a batch file that downloads a file from a website and I have added a line that will write text to a log file if there is an error ie no network or website unavailable but the Internet Explorer windows remains open after the batch file ends
Can someone tell me how I can have the Internet Exporer window to close if there is no network connection or the website is unavailabe.

Thanks
GingerAre you going to let us see the batch file, or not?
Quote from: Salmon Trout on September 04, 2010, 10:36:35 AM

Are you going to let us see the batch file, or not?

My cat is called Ginger.
Corruption once again.

Anyway, Ginger, you could try something in the likes of
CODE: [Select]IF pingDoesntSucceed
DO exit iexplorer
(I don't know, I'm just giving some tips here).
Quote from: Big on September 04, 2010, 08:47:23 PM
Corruption once again.

Anyway, Ginger, you could try something in the likes of
Code: [Select]IF pingDoesntSucceed
DO exit iexplorer
(I don't know, I'm just giving some tips here).


That would be the general idea. (will probably use tskill/taskkill iexplore or something to that effect). Ping seems to give an errorlevel of 1 if the host is not found. (although for some reason it is able to resolve www.sdkjfksdhfkjshdjf.com, and thinks it exists (?)) It would probably take additional checking with things like ipconfig to be sure that there isn't a internet connection at all (since invalid hosts still seem to resolve, but that might just be my DNS). Another problem is that most task kill programs kill all open tasks of that program, so killing the single process of internet explorer that was started isn't quite as simple as it seems at first glance- you wouldn't want the person running the batch to be using internet explorer (or even worse, a program using IE as  an out of process COM component) and suddenly kill all instances of IE. Only other way is to provide the window title, but IE changes it's window title in such a way that it's somewhat difficult to predict. Ideal solution might require a third-party "APPLICATION starter" that allows you to get the Pid of the program, which can be used by tskill to kill a specific instance.I think, rather than ponder how to close the right instance of Internet Explorer, I would rather avoid opening it at all, and use something like wget or curl, or a vbscript to find out if the network connection, website and desired file are all available, if so to get the file, if not to take appropriate action.

Quote from: Salmon Trout on September 05, 2010, 12:31:40 AM
I think, rather than ponder how to close the right instance of Internet Explorer, I would rather avoid opening it at all, and use something like wget or curl, or a vbscript to find out if the network connection, website and desired file are all available, if so to get the file, if not to take appropriate action.



For some reason that never even occurred to me, even though at the time I replied I was working on a CLASS that does something very similar in C#. Code: [Select]F:\>ping www.slkqjdfmlkjsdf.com
Ping request could not find host www.slkqjdfmlkjsdf.com. Please check the name a
nd try again.
Quote from: Big on September 05, 2010, 09:07:40 AM
Code: [Select]F:\>ping www.slkqjdfmlkjsdf.com
Ping request could not find host www.slkqjdfmlkjsdf.com. Please check the name a
nd try again.

Code: [Select]C:\Users\BC_Programming>ping www.slkqjdfmlkjsdf.com

Pinging www.slkqjdfmlkjsdf.com [67.215.65.132] with 32 bytes of data:
Reply from 67.215.65.132: bytes=32 time=87ms TTL=55
Reply from 67.215.65.132: bytes=32 time=86ms TTL=55
Reply from 67.215.65.132: bytes=32 time=85ms TTL=55
Reply from 67.215.65.132: bytes=32 time=100ms TTL=55

Ping statistics for 67.215.65.132:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 85ms, Maximum = 100ms, Average = 89ms

Quote
since invalid hosts still seem to resolve, but that might just be my DNS


I'm pretty sure it is.
Let's have a try...

Code: [Select]C:\>ping www.slkqjdfmlkjsdf.com

Pinging www.slkqjdfmlkjsdf.com [81.200.64.50] with 32 bytes of data:
Reply from 81.200.64.50: bytes=32 time=29ms TTL=56
Reply from 81.200.64.50: bytes=32 time=36ms TTL=56
Reply from 81.200.64.50: bytes=32 time=28ms TTL=56
Reply from 81.200.64.50: bytes=32 time=32ms TTL=56

Ping statistics for 81.200.64.50:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 28ms, Maximum = 36ms, Average = 31ms

Hmmm... try a tracert...

Code: [Select]C:\>tracert 81.200.64.50

Tracing route to advancedsearch.virginmedia.com [81.200.64.50]
over a maximum of 30 hops:

  1     7 ms    22 ms    37 ms  10.25.252.1
  2     8 ms    37 ms    16 ms  aztw-geam-1b-ge210.network.virginmedia.net [80.1.243.133]
  3    48 ms    29 ms    23 ms  aztw-core-1b-ae0-0.network.virginmedia.net [80.1.241.13]
  4     8 ms     9 ms    37 ms  brhm-bb-1b-as1-0.network.virginmedia.net [213.105.175.161
  5    52 ms    79 ms    69 ms  manc-bb-1a-as6-0.network.virginmedia.net [62.253.185.134]
  6    14 ms    39 ms    14 ms  manc-bb-1b-ae5-0.network.virginmedia.net [213.105.174.186
  7    34 ms    25 ms    36 ms  te-4-3.ar3.CDG2.gblx.net [204.246.200.177]
  8    29 ms    28 ms    29 ms  64.214.140.138
  9    30 ms    41 ms    37 ms  advancedsearch.virginmedia.com [81.200.64.50]

Trace complete.
Quote from: Tracert output
advancedsearch.virginmedia.com

Aha!







Code: [Select]C:\>ping www.slkqjdfmlkjsdf.com
Ping request could not find host www.slkqjdfmlkjsdf.com. Please check the name and try again.
That's better.

Quote from: BC_Programmer on September 05, 2010, 09:12:30 AM

I'm pretty sure it is.


Sure looks that way

Code: [Select]C:\>tracert 67.215.65.132

Tracing route to hit-nxdomain.opendns.com [67.215.65.132]
over a maximum of 30 hops:

  1    64 ms    14 ms     8 ms  10.25.252.1
  2    45 ms    19 ms   233 ms  aztw-geam-1a-ge147.network.virginmedia.net [80.1.243.1]
  3    33 ms    10 ms    11 ms  aztw-core-1a-ae0-0.network.virginmedia.net [80.1.241.9]
  4    50 ms    31 ms    34 ms  winn-bb-1a-as0-0.network.virginmedia.net [213.105.175.157]
  5    12 ms    44 ms    12 ms  brnt-bb-1b-as5-0.network.virginmedia.net [213.105.172.234]
  6    59 ms    16 ms    16 ms  195.50.91.129
  7    47 ms    17 ms    35 ms  ae-32-52.ebr2.London2.Level3.net [4.68.117.62]
  8    17 ms    70 ms    45 ms  ae-3-3.ebr1.London1.Level3.net [4.69.141.189]
  9    28 ms    15 ms    50 ms  ae-100-100.ebr2.London1.Level3.net [4.69.141.166]
 10    41 ms    31 ms    23 ms  ae-48-48.ebr2.Amsterdam1.Level3.net [4.69.143.81]
 11    68 ms    27 ms    24 ms  ae-2-52.edge4.Amsterdam1.Level3.net [4.69.139.170]
 12    35 ms    46 ms    65 ms  SPLICE-COMM.edge4.Amsterdam1.Level3.net [212.72.40.98]
 13    23 ms    54 ms    57 ms  hit-nxdomain.opendns.com [67.215.65.132]

Trace complete.
252.

Solve : Command vs Batch file?

Answer»

I am using the MOVE command, but running in to a problem.  If I put the command in to a Command WINDOW it works fine, but from a batch file I get errors.  Why?  I am running on a Windows 7(64 bit).

move /Y C:\#CAMS\Download\DST_exe\*.* C:\%Backup\DST\

If I use this at a DOS prompt it works great. 
If I use it in a batch file I get the messages "Cannot move multiple files to a single file"

Both folders do exist, and there are multiple files in them.

Maybe there is a better way.  What I am doing is moving file I download then extract files from (exe files and zip files)  to a different directory.  For example, all DST Files are an EXE file that is then ran and put in a 'DST_Work' folder for the DATABASE to PROCESS.  I clear the 'Work" folder, but I want to archive the files in the "DST_exe" folder.  I have 5 vendors like this.  Some are exe, some are zip, and another uses a different format.

Any advice is appreciated.

MichaelThere's a number of syntax problems with your line of code.

% needs to be escaped as %%. Better yet, you shouldn't use this character in folder or file names...

You should also surround your paths with QUOTATION marks, so the command doesn't screw up when it encounters a space.

move /Y "C:\#CAMS\Download\DST_exe\*.*" "C:\%%Backup\DST\"

If Backup is supposed to be an expanded variable, it's because you forgot the second %.

move /Y "C:\#CAMS\Download\DST_exe\*.*" "C:\%Backup%\DST\"

You see, % is USED in expanding DOS variables.

253.

Solve : Reproduce unicode from text file??

Answer»

I'm writing a script which I want to support reading unicode paths from a text file. I want all the unicode to be reproduced the same as pasting the characters into DOS where it appears as a square-like character. (DOS has no problem dealing with unicode characters, they just can't be displayed and this is fine.)

Type will not reproduce unicode from a text file properly, regardless of the file's encoding and the current code page. For cannot process type's junky unicode output which makes it impossible to stick in a variable. For has no problem with pasted unicode as aforementioned...

So far:
I open cmd.exe /u so I can redirect a unicode path to a text file. This encodes it as UTF-16LE. Let's say I have the path containing the Japanese hiragana "ki". The path and UTF-16LE-encoded text file look like this:
"C:\Folder き"

Basically, I need a utility that works like type to read the text file and reproduce this string properly, as-is. I was told gawk might be able to do it, but I don't have a clue where to start with gawk.

Can anyone who knows vbscript accomplish this in vbscript? If it can't output the text properly to command prompt, if it can at least send the lines properly as arguments to an executable, that would be okay. I found this (second half, Unicode to ASCII) but don't know how much it could help. I've spent hours on this scouring the web and I've found next to nothing. Help please! Thanks!I am not sure I understand what you are trying to say in your description, but I do understand the question in the subject so THATS what I am going to answer.

I think in order to turn a ASCII text file into a unicode text file, you simply need to rewrite the file with every 2nd byte a null character. I might be wrong. If I am not, this could probably be accomplished in almost any programming language that supports file IO. In VB you could allocate two byte arrays. One of which twice the size of the other. The file could then be read into the first array and then copied to every other byte in the second array. Then every 2nd byte in the 2nd array could be set to 0. Finally, the second array could be written back to the file or to a new file if necessary.

If it is confirmed that my reasoning is correct, then I would write the code for you. I am just not sure that this is the correct way to convert.Thanks for responding. As you thought, you're not on the right track. Btw, Japanese characters overwrite that 00 padding, as part of unicode.

I have a text file encoded as UTF-16LE containing the following:
"C:\Folder き"

I want to type this file in a batch script to the same effect as typing set MYVAR="C:\Folder き" manually in command prompt, where the き character would appear as a square (which means the character is there, it just can't be displayed). But as I described, the type command only works properly with ANSI text files, and type-ing the text file within a for loop to set the output to a variable does not work - for fails. For works fine when entering the text manually as I described though. It leads me to believe it's how type outputs the characters based on the current code page, which is apparently not the same.

Again, I believe I just need a vbscript or something that can output the text file properly - in the same character coding context as doing it manually.

Edit: I should probably show what I'm describing after all, lol.

for /f "delims=" %%x in ('type unicode_path.txt') do set myvar=%%x

Does not do anything, because type is outputting sloppy ANSI/code-page interpreted unicode and for doesn't like it.

I think it would be a command prompt REVOLUTION of sorts if you could code a vbscript which works! This is a big issue! lol

I'm likely to reproduce my big script in PowerShell once it's done (I'll still complete it, unicode or not), but I'd like to exhaust any options first.Is this sufficient? It just reads a text file into the command prompt. There is a way to make it take the file name as an argument, but I can't remember that part right now. You probably could have done that yourself, but i figured I would respond anyway. I might be able to come up with something better later if needed. I am using a MAC now.

Code: [Select]Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\blablabla.txt", 1)
Do Until objFile.AtEndOfStream
Wscript.Echo objFile.ReadLine
Loop
objFile.Close

EDIT: Be aware that you have to run this using cscript not wscript or it will just pop up a messagebox.I don't know vbscript at all actually, it's one of those things I can read but can't write.

I only need to process one file, so it doesn't need to accept a file name for an argument, but it does need to work with relative paths so hopefully that's not a problem.

I tested it and it's reading the text file similar to type, bad encoding. The only difference being that I can manipulate the output in for, so that's a good sign that it could just require some encoding work next.

There might be some vbscript clues in the link in my original post:

http://www.xtremedotnettalk.com/showpost.php?p=457931&postcount=7

Here is what they all output. UNI is the unicode file I'm working with. UTF is the unicode file converted to UTF-8. I also changed code pages from the default to UTF-8 just to see:



One more thing, if type utf.txt under the UTF-8 code page would work with for, that would almost solve the problem, except that I'd need a utility to convert the UTF-16LE file to UTF-8, and changing to code page 65001 makes batch scripts exit...  

I think I did it. I decided to program it in c because I thought this may be a useful tool for other people to use and it seems more official to make an exe tool. I know you said you didn't need it to take arguments, but I added one anyway just encase someone else needs it.

I've attached the exe and code below.

[recovering disk space - old attachment deleted by admin]I just realized that what I posted might not work. Do you just want all the unicode characters removed from the string or do you want to replace them with a space or a box or what?

I will reply with new code when you confirm this. I have already put way too much time into this thread so bear with me until I can figure this out.If you  can use Python,
Code: [Select]import codecs
import sys
inputfile=sys.argv[1]
f = codecs.open( inputfile, "r", "utf-16" )
for line in f:
   print line

output
Code: [Select]C:\test>more i.am.utf16.file.txt
here i am , utf-16 encoded file

C:\test>file i.am.utf16.file.txt
i.am.utf16.file.txt; Little-endian UTF-16 Unicode text, with no line terminators

C:\test>od -c i.am.utf16.file.txt
0000000       ■   h  \0   e  \0   r  \0   e  \0      \0   i  \0      \0
0000020   a  \0   m  \0      \0   ,  \0      \0   u  \0   t  \0   f  \0
0000040   -  \0   1  \0   6  \0      \0   e  \0   N  \0   c  \0   o  \0
0000060   d  \0   e  \0   d  \0      \0   f  \0   i  \0   l  \0   e  \0
0000100  \n  \0
0000102


C:\test>python test.py i.am.utf16.file.txt
here i am , utf-16 encoded file


its so much easier Quote from: Linux711 on September 08, 2010, 03:31:39 PM

I just realized that what I posted might not work. Do you just want all the unicode characters removed from the string or do you want to replace them with a space or a box or what?

I will reply with new code when you confirm this. I have already put way too much time into this thread so bear with me until I can figure this out.

Thanks for your help Linux but you're still misunderstanding what's required.

If you have Windows, open a command prompt window and paste this:

Code: [Select]for /f "usebackq delims=" %x in ('"C:\Folder き"') do set myvar=%x
This sets myvar to "C:\Folder き". The き character is displayed as a square, but it is still read as き.

Do this to save a text file unicode.txt as UTF-16LE (Unicode) containing "C:\Folder き":

Code: [Select]%ComSpec% /u /c echo:"C:\Folder き">unicode.txt
Then try this:

Code: [Select]for /f "delims=" %x in ('type unicode.txt') do set myvar=%x
Does nothing because type fails. Then try:

Code: [Select]type unicode.txt
You will see that this does not output "C:\Folder き", but instead:

Code: [Select]  C : \ F o l d e r   M0"
So I need something that will output "C:\Folder き".

ghostdog74: I'll try your code as well. Thanks!ghostdog74, I installed Python 3.1.2 and saved your script as read.py.

My UTF-16LE file uni.txt contains:
"C:\Folder き"

Both files are inside the current directory.

This is my MS-DOS command prompt:



What am I doing wrong? Quote from: orange_batch on September 08, 2010, 11:15:00 PM
What am I doing wrong?
if you are using Python 3.1 ++, the print statement is now a function, so add brackets.
Code: [Select]import codecs
import sys
inputfile=sys.argv[1]
f = codecs.open( inputfile, "r", "utf-16" )
for line in f:
   print(line)
And Python is particular about indentation, so indent properly.I'm not 100% sure how much better it would be as an alternative but following your example, I used more < unicode.txt and I got this:

Code: [Select]D:\>more < unicode.txt
"C:\Folder ?"

So I thought- maybe changing the codepage and THEN using this more to do it will work?

Code: [Select]D:\>chcp 65001
Active code page: 65001

D:\>more < unicode.txt
Not enough memory.

That was certainly an unexpected result. I wasn't able to get anything useful out of it either. ( tried copy unicode.txt con as well, which gave the same result as the type command). I found the fact that more wasn't displaying it spaced out and had a question mark rather then the ASCII-i-fied unicode promising, but redirecting that to a text file, even if I used the /u switch to start cmd still resulted in ASCII, with the double-byte character being converted to a question mark.

Personally, I'd go with GhostDog's solution.


Quote from: orange_batch on September 08, 2010, 11:15:00 PM
ghostdog74, I installed Python 3.1.2 and saved your script as read.py.

My UTF-16LE file uni.txt contains:
"C:\Folder き"

Both files are inside the current directory.

This is my MS-DOS command prompt:



What am I doing wrong?
I think the codecs package/import is deprecated, or at least the codecs.open routine is, in python 3.1 and later.

works in activestate perl 2.6.4... or, to be more precise, it runs. (without a syntax error, not sure why you are getting that)

I do get this though:

Code: [Select]D:\>python D:\test.py unicode.txt
Traceback (most recent call last):
  File "D:\test.py", line 5, in <module>
    for line in f:
  File "C:\Python\lib\codecs.py", line 679, in next
    return self.reader.next()
  File "C:\Python\lib\codecs.py", line 610, in next
    line = self.readline()
  File "C:\Python\lib\codecs.py", line 525, in readline
    data = self.read(readsize, firstline=True)
  File "C:\Python\lib\codecs.py", line 472, in read
    newchars, decodedbytes = self.decode(data, self.errors)
  File "C:\Python\lib\encodings\utf_16.py", line 90, in decode
    raise UnicodeError,"UTF-16 stream does not start with BOM"
UnicodeError: UTF-16 stream does not start with BOM
for some reason the command prompt doesn't redirect it's unicode output with a Byte Order Marker. I did a little looking to see if there was a way to specify to the open method to pretend there isn't a BOM and go with either LE or BE ordering, but my search was fruitless.

It appeared to work for ghostdog, so I assume we are both doing something incorrect- your version is too new (no idea wether this is really the case) and probably changed something, whereas I... well, I'm not sure what I did wrong. perhaps I made the unicode file incorrectly.

Updated. Same here BC.

BC, Orange,  first of all, the cmd.exe shell does not support utf-16, so its no use using it to run your script (although Python does process it normally at the back end). Secondly, I am using Python 2.6.x.  so i am not sure about Python 3.1.X but, here's another method

Code: [Select]data = open("c:\\test\\file1", 'rb').read()
decoded  = data.decode('utf-16')
print decoded

try the above using the Python Windows editor (comes with distribution) or some other platform that can display unicode..
I only know the tip of the iceberg of unicode so for more information, check with the docs

1) Unicode how to
2) codecs module
3) search at stackoverflowWell, the script itself is not unicode (DOS fails spectacularly with that), but it deals with path names which might contain unicode.

Microsoft knows some dirty secret about this unicode business.



Still not working ghostdog. But I'm not disheartened, because jeb on DosTips.com made me realize a fair enough workaround:

First of all, I'm only dealing with folder names, but this can be applied to files as well.

Forget the whole cmd /u thing and it outputs the ? in place of unicode as usual. ? matches any single character in a path, including unicode.

Retrieve the unicode in a folder name:
for /d %%x in ("C:\Folder ?") set folder="%%x"

(or retrieve the unicode in a file name:)
for %%x in ("C:\file ?") set file="%%x"

There are two problems however:

1. "C:\Folder ?" will match both "C:\Folder き" and "C:\Folder こ", etc.

2. for /r "C:\Folder ?"... does not work. Other things might not work either, without retrieving the unicode.
Solution: pushd "C:\Folder ?" then for /r with no "path" (processes current directory) then popd.

For the first problem, we can detect if it returns more than one result or not. If it does, have the user choose between which folders during run-time. This would have to verify each folder containing ? from the root folder to the most descendant folder. Parent folders can be filtered further by their descendants, unless the descendant folders exist in both parents, or something to that effect. I'm going to figure it out and work on a script for this.

It's the best that can be done. If anyone who comes across this can manage a solution to the original problem, it would still be desired.
254.

Solve : How to get back to the command line??

Answer»

Assume I have one EXCEL file locates at H:\My Documents\Docs\X.xls. I start it by command "CALL H:\My Documents\Docs\X.xls". After X.xls is started, the command line can not accept NEW input until the X.xls file closed. Is there any SOLUTION to get back to command line and make the new input workable and meanwhile no need to close X.xls? Thanks!H:\My Documents\Docs\X.xls just thatDont USE call, use start
Thanks you two friends!! Both of your solutions work well!!

255.

Solve : Batch File- Delete Files (Folder Name is a Variable)?

Answer»

So to make this as simple as possible...

Our department is running WINXP X86, SP3. The PROBLEM I am having pertains to Outlook 2007. When opening attachments, Outlook 07 dumps the attachment into a temp folder. The location can be found in the registry key. When this folder reaches maximum CAPACITY, Outlook will no longer allow attachments to be opened. Ultimately, my question is can a batch file be created to erase files from a folder that has a randomly assigned name? Or, instead, can a batch file be created to change the registry key VALUE, so the OLK cache folder can be assigned a specific name? Then, I believe I could create a batch file to be used universally on all of our desktops that WOULD empty the temp folder. Any feedback would be appreciated. Quote

So to make this as simple as possible...

Simple is good, but the post is a little short on specifics. It would have been nice to know the registry key.

You can use the reg query utility to extract the directory name from the registry and then use the del command with a wildcard.

Something like his may help:

Code: [Select]echo off
for /f "skip=2 tokens=3" %%i in ('reg query HKLM\system\currentcontrolset\services\tcpip\parameters  /v databasepath') do echo del %%i\*

The registry key is the path found in the left pane of the regedit program. The /v switch value is the name field found in the right pane of the regedit program. The value returned by the for statement is the data field in the right pane of the regedit program.

The code snippet contains an echo instruction to prevent any deletions until you are satisfied the returned directory is valid. Remove when you are ready. The snippet can be modified to delete the files (attachments) individually in case you need to keep some based on name or date or whatever.

Good luck. 
256.

Solve : datestamp help?

Answer»

hi all - I need a batch file to search in a directory. If all the files have the current date stamp then execute command1 if files are not current then execute command2.
thank you.This can be done via Perl or a number of other languages which have abilities to compare STRINGS, but I cant see doing this in raw batch. Quote from: DaveLembke on September 21, 2010, 10:10:00 PM

This can be done via Perl or a number of other languages which have abilities to compare strings, but I cant see doing this in raw batch.

It is a commonplace everyday task for batch. It can easily be done... using FOR and the ~t variable modifier you can get the "date" (created or last modified?) of each file, and it is trivially easy to get today's date.

However we do not know the OP's local date format or the format returned on his system by ~t

The output of this script will TELL us those things.

Code: [Select]echo off
echo local date format [%date%]
echo.>temp$$$
for /f %%A in ("temp$$$") do echo file date  format [%%~tA]
del temp$$$
pause


For example, I get this

Code: [Select]local date format [22/09/2010]
file date  format [22/09/2010 07:46 AM]
But I am worried about this in the question

Quote
I need a batch file to search in a directory. If all the files have the current date stamp then execute command1 if files are not current then execute command2.
thank you.

All the files? What if 99 do and 1 does not? Likewise for the converse situation.

these files will ALWAYS have the same date. I guess we can look in one particular file to check for the date.
thanks Quote from: x3g on September 22, 2010, 07:58:01 AM
these files will always have the same date. I guess we can look in one particular file to check for the date.
thanks

So did you run my script?
your script works good but it is missing the logic I need.
Quote from: x3g on September 22, 2010, 09:44:19 AM
your script works good but it is missing the logic I need.


I asked you to run the script so I could see your local date format. Then I can make a script for you with the logic that you need.
ah here it is
local date format [Wed 09/22/2010]
file date  format [09/22/2010 11:14 AM]

thank you. Code: [Select]echo off
setlocal enabledelayedexpansion

REM Of course you UNDERSTAND you need to edit this
set foldername="S:\Test\Batch\After 03-07-2010\test-file-date"

set pdate=%date%
set today=%pdate:~4,10%

REM get file date of latest file in folder
for /f "delims=" %%A in ( ' dir /b /a-d /od %foldername% ' ) do (
set fdate=%%~tA
set fdate=!fdate:~0,10!
)

if "%fdate%"=="%today%" (
goto yes
) else (
goto no
)

:yes
echo YES!!!
rem Code to execute if file date is today
goto next

:no
rem Code to execute if file date is not today
echo NO!!!

:next
REM whatever happens next...

pause





this looks very promising. I'll let you know my feedback once I've tested.
Thank you.
the YES condition works great but the NO logic only works for files that are older than 1 day. If the latest files are from yesterday it will still run the YES logic. Quote from: x3g on September 22, 2010, 01:13:29 PM
the YES condition works great but the NO logic only works for files that are older than 1 day. If the latest files are from yesterday it will still run the YES logic.

are you quite sure about this? Because the test would be

if "09/21/2010"=="09/22/2010"

which should fail and therefore the else CLAUSE gets triggered.

Could you insert these diagnostic lines shown in red?


echo off
setlocal enabledelayedexpansion

REM Of course you understand you need to edit this
set foldername="S:\Test\Batch\After 03-07-2010\test-file-date"

set pdate=%date%
set today=%pdate:~4,10%

REM get file date of latest file in folder
for /f "delims=" %%A in ( ' dir /b /a-d /od %foldername% ' ) do (
        set fdate=%%~tA
        set fdate=!fdate:~0,10!
        )




echo today is %today%
echo fdate is %fdate%
echo comparing [%fdate%] with [%today%]


if "%fdate%"=="%today%" (
        goto yes
) else (
        goto no
        )

:yes
echo YES!!!
rem Code to execute if file date is today
goto next

:no
rem Code to execute if file date is not today
echo NO!!!

:next
REM whatever happens next...

pause


even though the files are dated 9/21/2010 fdate still shows 9/22

today is 09/22/2010
fdate is 09/22/2010
comparing [09/22/2010] with [09/22/2010]
YES
Press any key to continue . . .

are you quite sure there is no file dated 09/22/2010 in that folder, including hidden files?
I replaced the 9/21 files with some 9/14 & 9/20 files and get this

today is 09/22/2010
fdate is ~0,10
comparing [~0,10] with [09/22/2010]
NO
Press any key to continue . . .
257.

Solve : Replacing characters in a large amount of folders?

Answer»

Hi,

I'm having troubles renaming folders

a colleague has a large amount of folders that contain # and she wants to replace these characters to _

123#12#12raw --> 123_12_12raw

What I have done today as a QUICK fix was list all the folders in a txt
dir /b *#* > print.txt

then I opened this txt in excel and generated LINES for each folder and pasted these in a *.bat

move 123#12#12raw 123_12_12raw
move 123#12#13raw 123_12_13raw
.....

This worked perfectly but it is not very user friendly

Is there a way to use the move command with wildcards?

I tried
move *#*#* *_*_*
but this (probably obvious) doesn't work.

If I try to find the files like that it does work
dir /b *#*#*

I spent the last 2 hours googeling but didn't find a decent solution yet

I also tried to do something with
for %1 in (*#*) do move %1 xxxxxx
but I can't figure out how to alter the variable so that # gets replaced with _ in %1

Anyone with suggestions?

Thanks,

JupkeGot an answer onan other (car)forum 

Wanted to share it here as well

Code: [Select]C:\Users\Roel\test>FOR /F "tokens=1,2,3 delims=#" %A IN ('dir /b *#*') DO move %
A#%B#%C %A_%B_%C

C:\Users\Roel\test>move 2123#12#14 2123_12_14
Er zijn         1 map(pen) verplaatst.

C:\Users\Roel\test>move 22123#12#13 22123_12_13
Er zijn         1 map(pen) verplaatst.

C:\Users\Roel\test>what's all that weird euro language stuff?
Quote from: Salmon Trout on September 15, 2010, 01:03:22 PM

what's all that weird euro language stuff?


I 'm sorry, I forgot to paste only the relevant part, edited the code now

"Er zijn 1 map(pen) verplaatst." means 1 folder has been moved.An alternative, maybe: if you want to take folder names containing # and replace that character with _ why bother using move? Just get the folder name into a string variable, use the replace function of the SET command, and rename the folder with the new string. E.g

Code: [Select]echo off
setlocal enabledelayedexpansion
for /f "delims=" %%A in ('dir /b /ad *#*') do (
set oldname=%%A
set newname=!oldname:#=_!
echo renaming "!oldname!" to "!newname!"
REN "!oldname!" "!newname!"
)

To do all subdirectories change dir /b /ad to dir /s /b /ad

Before...

Code: [Select]C:\test>dir
 Volume in drive S is USBHD
 Volume Serial Number is 2C51-AA7F

 Directory of C:\Test
15/09/2010  08:45 PM    <DIR>          .
15/09/2010  08:45 PM    <DIR>          ..
15/09/2010  08:44 PM    <DIR>          folder#1
15/09/2010  08:44 PM    <DIR>          folder#2
15/09/2010  08:44 PM    <DIR>          folder#3
15/09/2010  08:44 PM    <DIR>          folder#4
15/09/2010  08:45 PM    <DIR>          folder#4#5#6#####7
15/09/2010  08:44 PM               215 test1.bat
               1 File(s)            217 bytes
               7 Dir(s)  188,506,218,496 bytes free

Code: [Select]c:\Test\>test1.bat
renaming "folder#1" to "folder_1"
renaming "folder#2" to "folder_2"
renaming "folder#3" to "folder_3"
renaming "folder#4" to "folder_4"
renaming "folder#4#5#6#####7" to "folder_4_5_6_____7"

After...

Code: [Select]C:\Test>dir
 Volume in drive S is USBHD
 Volume Serial Number is 2C51-AA7F

 Directory of C:\Test

15/09/2010  08:48 PM    <DIR>          .
15/09/2010  08:48 PM    <DIR>          ..
15/09/2010  08:44 PM    <DIR>          folder_1
15/09/2010  08:44 PM    <DIR>          folder_2
15/09/2010  08:44 PM    <DIR>          folder_3
15/09/2010  08:44 PM    <DIR>          folder_4
15/09/2010  08:45 PM    <DIR>          folder_4_5_6_____7
15/09/2010  08:48 PM               217 test1.bat
               1 File(s)            217 bytes
               7 Dir(s)  188,506,218,496 bytes free
Indeed, this also works, but the effect is in this case exactly the sale with move as rename here?

I'm not sure in win7 but I thought rename didn't work for folder in XP? Quote from: Jupke on September 15, 2010, 02:18:59 PM
Indeed, this also works, but the effect is in this case exactly the sale with move as rename here?

Yes, however move has a potential ambiguity that ren does not, viz:

move folder1 folder2 (if folder2 does not exist!) is equivalent to ren folder1 folder2; BUT if folder2 does exist, folder1 can be moved to be a subfolder of folder2, unless its attributes forbid this . However, ren only renames, never MOVES.

Quote
I'm not sure in win7 but I thought rename didn't work for folder in XP?

1. Where did you get that idea?
2. Could you not have done an experiment?
3. It works for all Windows, as far as I know, as long as you have the right permissions and the folder attributes allow it.

Code: [Select]G:\test>ver

Microsoft Windows XP [Version 5.1.2600]

G:\test>md testdir

G:\test>dir
 Volume in drive G is DATA1
 Volume Serial Number is 9476-662D

 Directory of G:\test

15/09/2010  22:42    <DIR>          ..
15/09/2010  22:42    <DIR>          testdir
15/09/2010  22:42    <DIR>          .
               0 File(s)              0 bytes
               3 Dir(s)  16,695,369,728 bytes free

G:\test>ren testdir cakes-and-coffee

G:\test>dir
 Volume in drive G is DATA1
 Volume Serial Number is 9476-662D

 Directory of G:\test

15/09/2010  22:42    <DIR>          ..
15/09/2010  22:42    <DIR>          cakes-and-coffee
15/09/2010  22:42    <DIR>          .
               0 File(s)              0 bytes
               3 Dir(s)  16,695,369,728 bytes free

G:\test>
258.

Solve : DOS opens Internet Explorer and...?

Answer»

I'm trying to figure out how to use DOS CODING to open up Internet Explorer and make it go to a specific site. I know to make it go to IE, I NEED something lie:

echo off
START xxx/xxx/xxx/xxx/IE.exe

But how do I get it to go to a specific website?if you want to use DOS to start IE and then go to specific website and then do nothing else, you might as WELL go to your "Start" button and launch it. Its faster that way. BUT if you want to go to the  website  and download stuff and maybe you want to schedule it, then use vbscript for native or use a tool such as wget/curl to do it.The web page is entered an an argument for IEXPLORE.EXE.  Use the following link to Google as an example:
Code: [SELECT](path to ie directory)\IEXPLORE.EXE http://www.google.com
Interesting, would you be able to link in multiple sites? Like using && and just link in more?

259.

Solve : Rename multiple files whose names are contained in an XML file.?

Answer»

Hi Guys,

I have a bunch of 'm4a' files that i need to RENAME, literally thousands, they're voice memos from my iPhone.

I have them stored on my hard disk in the directory 'C:\Memos'.

I have an xml file which contains the name of the file and the tag that the file should be called

The xml file contains all the file names, and all the tags that the files should be named.

I've included a sample of the xml file below to give a better idea of how it's structured.

 
 
-
-
  20090816 104438.m4a
  Autosleep
  20090816 124708.m4a
  Head pillow
 
 

So the file '20090816 104438.m4a' needs to be renamed 'Autosleep.m4a', the file '20090816 124708.m4a' needs to be renamed 'Head pillow.m4a' , etc.

Is there a way of doing this automatically with python or vbscript perhaps?

Any help or advice would be much appreciated as I am new to this and have been doing the renaming manually so far, but i've thousands of files to get through.

Thanks again,

JP
I'm sure you'll get a Python solution but I went with VBScript because it comes installed with Windows and there is no download required for those that won't or can't download third party products.

Code: [Select]Dim arrKey()
Dim arrString()

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
Set fso = CreateObject("Scripting.FileSystemObject")

xmlDoc.async = False
xmlDoc.load("c:\temp\ch.xml")    'change path\filename as required

Set KeyList = xmlDoc.documentElement.selectNodes("dict/key")
i = -1
For Each key in KeyList
  i = i + 1
  ReDim Preserve arrKey(i)
  arrKey(i) = key.text
Next

Set StringList = xmlDoc.documentElement.selectNodes("dict/string")
i = -1
For Each str in StringList
  i = i + 1
  ReDim Preserve arrString(i)
  arrString(i) = str.text
Next

For i = 0 To UBound(arrKey)
Set f = fso.GetFile(arrKey(i))
newName = arrString(i)
f.Name = newName & "." & fso.GetExtensionName(arrKey(i))
Next

There is probably a simpler way to do this with the XMLDOM object, but I chose to go with brute force. Save the snippet with a vbs extension and run from the command line as cscript scriptname.vbs Be sure to change the path\file name as required.

Good luck.  Here's a Python solution. Note you should really use an XML parser like lxml, but since your sample XML is simple enough.....
Code: [Select]import os
import sys
inputfile=sys.argv[1]
keys=[]
strings=[]
for line in open(inputfile):
    s=line.rstrip()
    if "<key&GT;" in s:
        keys.append(s[s.index(">")+1:].replace("</key>",""))
    if "<string>" in s:
        strings.append(s[s.index(">")+1:].replace("</string>",""))
for k,v in zip(keys,strings):
    try:
        print "Renaming %s to %s"%(k, v)
        os.rename(k,v)
    except OSError,e:
        print e
    else:
        print "Renamed %s to %s." %(k,v)


on command line
Code: [Select]c:\test> python myscript.py myxml.xml
Thanks a million for your help.

Having a slight problem here

The vb script is called 'memos.vbs', the xml file is 'C:\memo\l.xml'

When i run the script from command prompt using 'cscript memos.vbs' i get the error:

C:\memo.vbs(27,2) Microsoft VBScript runtime error: File not found'

Any advice on RESOLVING the above would be much appreciated! Thanks again for your help.

My script is:

Dim arrKey()
Dim arrString()

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
Set fso = CreateObject("Scripting.FileSystemObject")

xmlDoc.async = False
xmlDoc.load("C:\memo\l.xml")    'change path\filename as required

Set KeyList = xmlDoc.documentElement.selectNodes("dict/key")
i = -1
For Each key in KeyList
  i = i + 1
  ReDim Preserve arrKey(i)
  arrKey(i) = key.text
Next

Set StringList = xmlDoc.documentElement.selectNodes("dict/string")
i = -1
For Each str in StringList
  i = i + 1
  ReDim Preserve arrString(i)
  arrString(i) = str.text
Next

For i = 0 To UBound(arrKey)
   Set f = fso.GetFile(arrKey(i))
   newName = arrString(i)
   f.Name = newName & "." & fso.GetExtensionName(arrKey(i))
Next Thanks ghostdog!

The python scrit doesn't give the files the 'm4a' extension, but does change all the file names to the correct tag.

Is there a way to change the extension of multiple files, or perhaps include it in the python script?

Thanks again,

Jp Quote from: jpm999 on September 11, 2010, 07:43:03 PM

Thanks ghostdog!

The python scrit doesn't give the files the 'm4a' extension, but does change all the file names to the correct tag.

Is there a way to change the extension of multiple files, or perhaps include it in the python script?

Thanks again,

Jp

then add the string ".m4a"
Code: [Select]os.rename(k,v+".m4a")
Its not that difficult. Now, go read up Python docs.
260.

Solve : How to keep FTP connection alive in command line??

Answer» HI Friends,

As you know, in default, FTP connection time out is 120 seconds. It is very boring to re-connect frequently. So is there any way to make ftp connection alive for specified long time or for ever until close it explicitly?

I often encountered the following boring message:
Connection CLOSED by REMOTE host.

Hope you can help me out of this TROUBLE!! Thanks!!possibilities, FTP server configured to close connection after certain time of idling, OR a firewall in between can close the connection.
261.

Solve : shortcut keys for copy and paste in command line?

Answer»

Hi Friends,

not sure if there are some shortcut keys for COPY and paste content in command line?

normally, I must use right click->mark->select TARGET text->enter to copy target text and right-click->paste.

it is boring to do so even it is frequent, so could you please do me a favor on this?

THANKS!If you enable the Quick EDIT Mode, and Insert Mode properties in the command WINDOW, then you can select the text with the left mouse button, click the right button to copy, and again to paste.

262.

Solve : "For" and "If" command doubt?

Answer»

Hi,

This is my first post. I'm here for asking a question about a doubt I can't solve. I've already read most of on line help available, but I cannot do my batch work correctly.

This batch should look for every *inside.jpg files under my Music folder and if the file "Front Cover Inside.jpg" doesn't exist it should rename *inside.jpg file to "Front Cover Inside.jpg".
But if "Front Cover Inside.jpg" exist and there's some *inside file, it should log "Similar file to '*inside.jpg' already exists"

My batch:
Code: [Select]for /R %%x in (*inside.jpg) do if not exist "Front Cover Inside.jpg" (
ren "%%x" "Front Cover Inside.jpg"
echo "%%x" renamed to "Front Cover Inside.jpg" >> Log.txt
) ELSE (
echo Similar file to "%%x" already exists >> Log.txt
)

PS: Log.txt file already exists. I'm working on a Windows XP Professional SP3 machine.I just ran your script twice, and the first time, it renamed "0D0A inside.jpg" to "Front Cover Inside.jpg", and added this line to log.txt

"S:\Test\Batch\After 03-07-2010\for-if\0D0A inside.jpg" renamed to "Front Cover Inside.jpg" 

The second time it did nothing and wrote this line

Similar file to "S:\Test\Batch\After 03-07-2010\for-if\Front Cover Inside.jpg" already exists

Isn't this what you want?

Quote from: Salmon Trout on September 08, 2010, 02:13:06 PM

I just ran your script twice, and the first time, it renamed "0D0A inside.jpg" to "Front Cover Inside.jpg", and added this line to log.txt

"S:\Test\Batch\After 03-07-2010\for-if\0D0A inside.jpg" renamed to "Front Cover Inside.jpg" 

The second time it did nothing and wrote this line

Similar file to "S:\Test\Batch\After 03-07-2010\for-if\Front Cover Inside.jpg" already exists

Isn't this what you want?

My problem is when "Front Cover Inside.jpg" coexists with some file like "0D0A inside.jpg".
What I want to be logged is:
Code: [Select]"Similar file to "S:\Test\Batch\After 03-07-2010\for-if\0D0A inside.jpg" already exists" which in this case is "Front Cover Inside.jpg").

Then, after reading the log, I will manually check which file is "0D0A inside.jpg" and if it's quality is better than "Front Cover Inside.jpg" it will delete this one.
I need this because I have thousands of album art files I don't want to check then one by one...

TIAFinally I think I've solved my problem. My final batch looks like this:

Quote
echo off
for /R %%x in (*-inside.jpg) do if not exist "Front Cover Inside.jpg" (
ren "%%x" "Front Cover Inside.jpg"
if errorlevel 1 (
echo Similar file to "%%x" already exists >> Log.txt
goto end
)
echo "%%x" renamed to "Front Cover Inside.jpg" >> Log.txt
)

:end

The trick is using errorlevel. When trying to rename the file, if there's already a file with the same name, MS-DOS will return a error message. I've just use this to sove my problem.
I've tried different scenarios and it worked the way I want it. So, I'm proud of myself, considering how newbie I'm in MS-DOS command line... Quote from: vitorb on September 11, 2010, 07:40:29 AM
Finally I think I've solved my problem. My final batch looks like this:

The trick is using errorlevel. When trying to rename the file, if there's already a file with the same name, MS-DOS will return a error message. I've just use this to sove my problem.
I've tried different scenarios and it worked the way I want it. So, I'm proud of myself, considering how newbie I'm in MS-DOS command line...


This is going to start driving me completely INSANE. Quote from: BC_Programmer on September 11, 2010, 08:33:52 AM

This is going to start driving me completely insane.

  Sorry... You're completely right! I know that MS-DOS it's a operating system and what I'm using is just a command line interpreter.
Ten YEARS ago I USED MS-DOS for a few months, but I never developed any SKILLS on it's usage...And the tweaking goes on...

My previous batch had one problem. This code:
Code: [Select]for /R %%x in (*inside.jpg) do if not exist "Front Cover Inside.jpg"doesn't seems to work correctly because after the batch finish I saw that every "Front Cover Inside.jpg" files in various directories had been renamed again to it's current name.

Code: [Select]ren "%%x" "Front Cover Inside.jpg"Whenever %x is "Front Cover Inside.jpg" it will be:
Code: [Select]ren "Front Cover Inside.jpg" "Front Cover Inside.jpg" which is useless...

So I've change it this way:
Code: [Select]for /R %%x in (*inside.jpg) do if "%%~nxx"=="Front Cover Inside.jpg" (
echo "Front Cover Inside.jpg" already exists
) else (
ren "%%x" "Front Cover Inside.jpg"
if errorlevel 1 (
echo Similar file to "%%x" already exists >> Log.txt
) else (
echo "%%x" renomed to "Front Cover Inside.jpg" >> Log.txt
)
)
263.

Solve : sorting folders according to content file extension!?

Answer»

Hello .. guys..

As i cannot find any batchfile wich can do my job,and
since i got a unsorted folder with more then 20000 files to be sorted, i am TIRED of doing it manualy
can or is it possible to batch this.
can some one tell me if this is possible in a msdos batch file ..
folders has more then one files but particular file extensions makes my decision where to put the folder.
this is the situation in unsorted
 
\---root
    +---sorted
    |   +---te1
    |   +---te2
    |   \---te3
    \---unsorted
        +---folder1
        |       pre.te3
        |       
        +---folder2
        |       pre.te1
        |       
        \---FOLDER3
                pre.te2

this is what i want to end up sorted all files in the corrsponding folders.

|   
\---root
    +---sorted
    |   +---te1
    |   |   \---folder2
    |   |           pre.te1
    |   |           
    |   +---te2
    |   |   \---folder3
    |   |           pre.te2
    |   |           
    |   \---te3
    |       \---folder1
    |               pre.te3
    |               
    \---unsorted


In short i wanne sort files  but keep the folder names in the new sorted map structure.

i have tried to use different aproaches like dir *.te1 /D/B/S > te1.log
and use this log file to sort, but got stuck on how to use this log in a "for" environement

help is appreciateddo you actually just need to view the output (at your screen) as sorted, or do you actually want to move the files from "unsorted" folder into the the "sorted" folder, then display them ? define your problem clearlymoving the folders as shown above.
or copy  and use the unsorted as backup.

i do not need to view the output
as i said in my first post just moving/copying into the sorted folder

The folder structure shown above is only to clearify my problem. Since words are sometimes not enough and misunderstood.

Quote from: mazhive on September 06, 2010, 12:27:02 PM

can some one tell me if this is possible in a msdos batch file ..
yes, its possible. My solution is not batch, so if you can install Python, here's a script you can use

Code: [Select]import os
import shutil
root="C:\\"
dirsortedpath=os.path.join(root,"test","sorted")  # put sorted path here
dirunsortedpath=os.path.join(root,"test","unsorted")  # unsorted path
os.chdir(dirsortedpath)
dirsorted = [ d.lower() for d in os.listdir(".") if os.path.isdir(d) ]
for r,d,f in os.walk(dirunsortedpath):
   for files in f:
      ext=files[-3:].lower() #get the extension
      if ext in dirsorted:
         try:
            shutil.move(r, os.path.join(dirsortedpath,ext))
         except Exception,e:
            print e
         else:
            print "moved .."
save as myscript.py on the command line
Code: [Select]c:\test> python myscript.py


If not, you can wait for your batch solution.that would be no problem.
thanx !!!! gone chek it out later this evening thanx... it seems that it moves only the file not the folder

so i get root\sorted\te1\xxxxxx.te1
not  root\sorted\te1\folder 3\xxxxx.te1

do i have to change more than only the sorted path and unsorted path.

thanx.. alot for this piece of code... i use cygwin to do some linux like stuf and it has python installed on default. Quote from: mazhive on September 09, 2010, 05:22:41 AM
it seems that it moves only the file not the folder

so i get root\sorted\te1\xxxxxx.te1
not  root\sorted\te1\folder 3\xxxxx.te1

do i have to change more than only the sorted path and unsorted path.

thanx.. alot for this piece of code... i use cygwin to do some linux like stuf and it has python installed on default.

you can always debug your script by using print . First comment out shutil.move line , then just insert a print statement
Code: [Select]print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
# shutil.move(r, os.path.join(dirsortedpath,ext))

see if its what you want. If yes, then the shutil.move should not be the problem.
sorry but i get an error message.

print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
                                                                        ^
IndentationError: unident does not match any outer indentation level

####BOF

import os
import shutil
root="C:\\"
dirsortedpath=os.path.join(root,"TEMP","batch","root","sorted")  # put sorted path here
dirunsortedpath=os.path.join(root,"TEMP","batch","root","unsorted")  # unsorted path
os.chdir(dirsortedpath)
dirsorted = [ d.lower() for d in os.listdir(".") if os.path.isdir(d) ]
for r,d,f in os.walk(dirunsortedpath):
   for files in f:
      ext=files[-3:].lower() #get the extension
      if ext in dirsorted:
      try:
   print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
#            shutil.move(r, os.path.join(dirsortedpath,ext))
         except Exception,e:
            print e
         else:
            print "moved .."

###EOF


I am using Nano to add or change a line of the python script.
 Python  is particular about indentation, so indent properly(use spaces, not tabs)

Code: [Select]import os
import shutil
root="C:\\"
dirsortedpath=os.path.join(root,"TEMP","batch","root","sorted")  # put sorted path here
dirunsortedpath=os.path.join(root,"TEMP","batch","root","unsorted")  # unsorted path
os.chdir(dirsortedpath)
dirsorted = [ d.lower() for d in os.listdir(".") if os.path.isdir(d) ]
for r,d,f in os.walk(dirunsortedpath):
   for files in f:
      ext=files[-3:].lower() #get the extension
      if ext in dirsorted:
          try:
              print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
             #shutil.move(r, os.path.join(dirsortedpath,ext))
          except Exception,e:
              print e
          else:
              print "moved .."

thanx i didn't know,... i am not that familiar with python scripting.

but now i got this,...

print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
                   ^
SyntaxError: Invalid syntax

i greatly appreciate your help and patience.
  Quote from: mazhive on September 09, 2010, 05:21:08 PM
thanx i didn't know,... i am not that familiar with python scripting.

but now i got this,...

print "Moving " r , " to ", os.path.join(dirsortedpath,ext)
                   ^
SyntaxError: Invalid syntax

i greatly appreciate your help and patience.
 

sorry, it should be
Code: [Select]print "Moving ", r , " to ", os.path.join(dirsortedpath,ext)

Now proceed to look at the Python documentations. Take the tutorial if you are not familiarthanx ,... hmm i feel like stupid right now ,....
now it doesn't move anything.
and no error... Quote from: mazhive on September 09, 2010, 06:13:35 PM
thanx ,... hmm i feel like stupid right now ,....
now it doesn't move anything.
and no error...
of course it doesn't because the shutil.move line is commented right ?? Uncomment the line when you are ready to move, but in the meantime, just use the print statements to see if you have got the correct files

 And what does your output SHOW? If you have print statements in your script, it will show when you run the script. If it did not show, then it shows that the

Code: [Select]if ext in dirsorted:
is not executed. Like i told you, if you are not sure, put in print statements to show the execution

Code: [Select]....
for r,d,f in os.walk(dirunsortedpath):
   for files in f:   
      print "now doing file: " , os.path.join(r,files)
      ext=files[-3:].lower() #get the extension
      print "Extension is ", ext
 .....
Just a question, will the folders only contain 1 file type?oke,..

well some TIMES it has 3 files but only 1 is important for me to decide
the actual extensions would be ,t64 ,d64 ,crt ,p00 ,prg with these files, sometime a txt file or nfo or doc are within that folder but that does not make my decision to move it in a folder
 so these te1 or te2 are just for experimental environment so i can use it in my actual folder and files later.

ghostdog... well thats the point it does do a output but doesn't move the folder now i put the other piece of code in it and it gives me output but no moved folders yet it moved the files.

###BOF

import os
import shutil
root="C:\\"
dirsortedpath=os.path.join(root,"TEMP","batch","root","sorted")  # put sorted path here
dirunsortedpath=os.path.join(root,"TEMP","batch","root","unsorted")  # unsorted path
os.chdir(dirsortedpath)
dirsorted = [ d.lower() for d in os.listdir(".") if os.path.isdir(d) ]
for r,d,f in os.walk(dirunsortedpath):
   for files in f:   
      print "now doing file: " , os.path.join(r,files)
      ext=files[-3:].lower() #get the extension
      print "Extension is ", ext
for r,d,f in os.walk(dirunsortedpath):
   for files in f:
      ext=files[-3:].lower() #get the extension
      if ext in dirsorted:
          try:
              print "Moving ", r , " to ", os.path.join(dirsortedpath,ext)
              shutil.move(r, os.path.join(dirsortedpath,ext))
          except Exception,e:
              print e
          else:
              print "moved .."

###EOF
264.

Solve : Change drive in CMD?

Answer»

I can't change drive by using D:

I tried using the CD command and specifying the full location but that doesn't work either.

Someone help a newbie out?
Are you positive that you have a drive D? Can you access it via WINDOWS explorer?Yes. It certainly is there. I'm using a windows 7 starter edition because I'm in a foreign country running a netbook, is that helpfull?What if you create a shortcut to cmd.exe and under the "Start in" field or something SIMILAR, type D:\. Now when you run that shortcut, does it work?If that doesn't work you could try command.com instead of cmd.exeThat "Start in" option worked. Now when I start up cmd I'm in the D partition... and I cannot change to my C drive. It keeps saying my syntax is not in order but all I type in is C: or I tried C:\ or CD C:\somefolder and hit returnthe way to change DRIVES is to type the letter, upper case or lower case, followed by a colon. A full colon like this :

Code: [Select]c:\>D:

D:\>
Quote

It keeps saying my syntax is not in order

What does it say exactly?

Is your keyboard OK? Is the layout SETTING right? Can you type colons? like this ::::::::::::::::::: Do you see them on the screen?

ANOTHER way to change drives is to use CD with the /D switch, Does this work?

Code: [Select]D:\>CD /D C:

c:\>
Ha! It was a keyboard settings thing. I bought this thing in Colombia, I'm not exactly Colombian. Tnx for the help.
265.

Solve : If statements in command line?

Answer»

Hi,

   I'm trying to create a command script(.cmd file) with if statements.I don't think the if statements work here.Because even though the first if condition fails,the CONTROL always goes to LAST STEP.

Also can you please explain how to do if<> and <>

Thanks and appreciate your help on this.

Here is the code:

ECHO ON

SET JOBNAME=TEST

for /F  %%G in ('sqlcmd -E -S TAMANS-SQ12DCL\SQL1A -d SalesInterface -h-1 -W -Q "set nocount on;SELECT count(*) FROM table_test"') do (echo %BATCH_QUERY%:%%G)


if %ERRORLEVEL% equ 0 if %BATCH_QUERY% gtr 0 (GOTO LASTSTEP)
if %ERRORLEVEL% NEQ 0 (GOTO ERROR1)

:LASTSTEP
echo **********************************************
echo * COMPLETION OK                        *
echo **********************************************
:NORMAL
ECHO SUCESSFUL Completion of ICV001.
SET ControlM=0
GOTO END


:ERROR1
echo **********************************************
echo * %JOBNAME% NOT OK                       *
echo **********************************************
echo %JOBNAME% Abended
REM THERE WAS AN ERROR!
SET CONTROLM=1
goto END


:END
ECHO %JOBNAME% done.

  Where does the variable %BATCH_QUERY% get a value?
from %%G after the query executes.

for /F  %%G in ('sqlcmd -E -S TAMANS-SQ12DCL\SQL1A -d SalesInterface -h-1 -W -Q "set nocount on;SELECT count(*) FROM table_test"') do (echo %BATCH_QUERY%:%%G)
Quote

from %%G after the query executes.

That does not set the value; it echoes %BATCH_QUERY%, a colon, and WHATEVER %%G happens to be. If you did not do

SET BATCH_QUERY=

before, it will be undefined (blank).




So,should it be like this......

set BATCH_QUERY=0

set BATCH_QUERY=for /F  %%G in ('sqlcmd -E -S test-SQ17CL\SQL1A -d SalesInterface -h-1 -W -Q "set nocount on;SELECT count(*) FROM table_test"') do echo %%G
Quote from: priyabala on September 20, 2010, 02:58:22 PM
So,should it be like this......

set set BATCH_QUERY=0

set BATCH_QUERY=for /F  %%G in ('sqlcmd -E -S test-SQ17CL\SQL1A -d SalesInterface -h-1 -W -Q "set nocount on;SELECT count(*) FROM table_test"') do echo %%G


If you want the output of the sqlcmd command to be assigned to the variable BATCH_QUERY you could do something like this

Code: [Select]for /F  %%G in ('sqlcmd -E -S test-SQ17CL\SQL1A -d SalesInterface -h-1 -W -Q "set nocount on;SELECT count(*) FROM table_test"') do set BATCH_QUERY=%%G
is it going to be a number?

Sorry about the delayed reply.

Yes, it is going to be a number.

Also,can you please let me know how to do multiple conditions in if statments.Is this correct.

if %ERRORLEVEL% equ 0 if %BATCH_QUERY% gtr 0 (GOTO LASTSTEP)
if %ERRORLEVEL% NEQ 0 (GOTO ERROR1)


Please let me know.I really appreciate your help on this.

Thanks.
Code: [Select]
REM put this test FIRST
if %errorlevel% neq 0 goto error1

REM You will only get here if errorlevel is 0
if %batch_query% gtr 0 goto laststep

REM If you get here errorlevel is 0 and batch_query is 0
REM What are you going to do?
REM Maybe goto end?
REM If you do nothing you will go to the next line.
REM Which is laststep...

:laststep
REM Your code
goto end

:error1
REM your code

:end


Also... in your code...

Code: [Select]echo %JOBNAME% Abended
REM THERE WAS AN ERROR!
SET CONTROLM=1
goto END


:END
1. The goto END statement is superfluous, because you are going there anyway.

2. "Abended" is not an ENGLISH word.



Thanks for all your replies.I'll try these.I have always found life easier if a script commences
ECHO OFF
or even
ECHO OFF

I rather doubt that there is any benefit from starting with
ECHO ON

Alan
266.

Solve : can a *.bat answer prompted the questions automatically for a program??

Answer»

I'm trying to make a batch file that will answer prompted questions automatically for a program.  I need to click "next" 4 times and click "enter".  Quote from: DaveIsRacerX on September 17, 2010, 07:42:21 PM

I'm trying to make a batch file that will answer prompted questions automatically for a program.  I need to click "next" 4 times and click "enter". 
Batch operates with a COMMAND LINE Interface. There is no way to click things with just batch. You will probably be able to ACCOMPLISH this with VBS, but not batch. Quote from: DaveIsRacerX on September 17, 2010, 07:42:21 PM
I'm trying to make a batch file that will answer prompted questions automatically for a program.  I need to click "next" 4 times and click "enter". 

Clicking "next" and "enter" sounds like you're DEALING with a GUI. Batch language barely knows Windows exists much less interacting with it. It is possible to create a response file for a command line program using redirection.

For a Windows program you can use VBScript and program the keys (no mouse movements) needed to accomplish the task. There is a discussion of this going on in this thread. Check it out.

Good luck.
267.

Solve : What values does the IF command compare??

Answer»

Win XP Home.  Batch script.

Newbie.

Does the If command COMPARE the ASCII decimal value when comparing strings?  If so why does the following return True when the ASCII values would show that the return should be False?

Thanks

Code: [SELECT]echo off
cls

if "2" gtr ";" echo 2 is greater than ;
The cmd.exe IF TEST does not do a plain ASCII comparison. Numerals come before letters; letters are normalized to lower case. For example 4 has a lower character value than 6, so 49 is LESS than 6.1 when compared as strings; ',' is less than ';', etc. ACCORDING to the byte value of the characters.

268.

Solve : Student stuck with batch files taht will not work, HELP?

Answer»

I have created several BATCH programs and saved them in a directory, updated my search PATH to include directory, and whenever i am in a different directory, the batch files do not WORK, why?1. What do you mean they "don't work"? Do you mean you cannot start them by typing the batch name, or that you can start them but they don't work in the WAY that you want them to?
2. What is this "search path"?
3. How did you "update" it?
If your talking about updating the PATH variable to include the directory with your batch files and after doing so, not being able to access the batch files, then. . .

You need to RESTART the comp.

269.

Solve : ftp commands?

Answer»

Hi all,

I'm cracking my head with a small and simple thing, that unfortunately seems out of reach for my head...
I need to transfer files from a ftp server to my computer in a automatic way. The problem is that the FOLDER in the ftp, were these files are, acts as a backup as well, having files with 3 weeks OLD. Is there a way of SORTING the files by date, and just download these ones instead of everything?

Thanks in advance

Regardsthe windows ftp client that came with INSTALLATION is primitive. Instead, use a programming language, eg Python (or any others) that provides you FTP libraries for file transfer. eg in Python
Code: [Select]import ftplib
server="localhost"
user="anonymous"
password="[email protected]"
filelist=[]
DEF download(ftp, filename):
    ftp.retrbinary("RETR " + filename, open(filename,"wb").write)
try:
   ftp = ftplib.FTP()
   ftp.debug(3)
   ftp.connect(server,21)
   ftp.login(user,password)
except Exception,e:
    print e
else:
    ftp.cwd("directory to change if any")
    ftp.retrlines('LIST',filelist.append)
    for latest in filelist:
        if latest.startswith("-") and "latest file pattern if any" in latest:
            print latest
            download(ftp,latest)
    ftp.quit()
sys.exit()

this assumes that your old files are named in a distinct format, such as file.bak or something, and your latest file is not in that format.

usage:
Code: [Select]C:\test> python myscript.py

270.

Solve : ms dos computer has 2 lost allocation units?

Answer»

Hello,

I need help.  When I start computer and it starts it setup it stops and has 2 LOST ALLOCATION UNITS FOUND 1 CHANINS.
CONVERT LOST CHANINS TO FILES Y-N, so here is where I should be ABLE to type and I can't. It will not let me do anything, so I restart computer and hit the key to go to the amibios simple setup utility(ver 1.19), but can't find anywhere in setup to RUN the -CHKDSK- for fix my PROBLEM.  I have read in many places on the web that this will fix computer, but can't get to a C: or a CHKDSK file.   
Any ideas would be amazing!  Thanks you Quote

so here is where I should be able to type and I can't. It will not let me do anything, so I restart computer

Is it a USB keyboard. Sometimes you have to go into the BIOS and enable Legacy USB for it to work.Yes, I do have a USB keyboard, will try. Thank you, I am running a PC DOS, don't know if it MAKES any difference.Sounds like System files are corrupted.  You'll have to boot to a Boot Disk and reinstall system files.
Get the version you need from here:  www.bootdisk.com
Boot to the floppy disk or CD.
Then type:  sys c:
Hit return.
Remove boot disk and restart computer.
271.

Solve : File name problem...?

Answer»

I have a batch file "Test.bat":
Code: [Select]echo on
msg * This is a test.
del Test.bat
pause

Well this script looks fine but if i change the file name "Test.bat" to "Testing.bat" (Not the name in script).
The script seems not to work. The error is:
Del Test.bat
Could Not Find C:\Test.bat

I need a script that can detect its own file name.
Could anyone help me find a way out of this problem?As long has you have not used the SHIFT command, then
%~f0
refers to the fully qualified name of the batch file
Thats a zero at the end btwI am sure a script can detect itself,
and can even copy itself,
but I would expect the O.S. to CONSIDER the file in use if it tried to move or delete itself.

Alan
It is certainly possible for a batch file to delete or rename itself, but there will be an error message when cmd.exe comes back from carrying out the del or ren command to find the script gone or renamed.

consider...

Code: [Select]C:\>echo del %~f0>test.bat

C:\>test.bat

C:\>del test.bat
The batch file cannot be found.
and...

Code: [Select]C:\>echo ren %~f0 test1.bat>test.bat

C:\>test.bat

C:\>ren test.bat test1.bat
The batch file cannot be found.



Quote from: ALAN_BR on September 24, 2010, 02:08:19 PM

I am sure a script can detect itself,
and can even copy itself,
but I would expect the O.S. to consider the file in use if it tried to move or delete itself.

Alan


Simply opening a file doesn't constitute "in-use".

The call to CreateFile() would need to explicitly lock the file, by not specifying any of the FILE_SHARE_X flags.

For example, if the CreateFile() is passed FILE_SHARE_READ, other programs can open the file for reading, but cannot write to the file or open it with write flags, or delete the file. FILE_SHARE_WRITE will allow programs to write to the file but not read or delete it, and FILE_SHARE_DELETE will allow the file to be deleted.

Larry Osterman writes about this, and although he doesn't explicitly note anything to do with batch files there is an implication there; he notes that by default, DOS applications would open files in a manner so that any other program could access them, because of the single-tasking nature of DOS nobody considered this to be a problem. Therefore it's safe to assume that CMD.EXE opens batch files in the same mode that command.com does- that is, in a mode whereby the file is free to be changed (FILE_SHARE_WRITE+FILE_SHARE_READ+FILE_SHARE_DELETE).

He also mentions that the NT Loader will open Executables with the FILE_SHARE_DELETE flag; this means that the file cannot be opened for READ or WRITE access by any program. additional invocations of the executable don't cause a problem, because the loader simply uses the same Mapped View of the executable file that it created the first time around.

It's not as cut-and-dried as "if the file is open, no other program can access it".

Wether that is truly the case for cmd, I don't know. It's entirely possible it opens the batch file, reads the next line, and then closes it, too.Sorry, you are right and I was wrong.

I was remembering past experiences before CMD.EXE and before Windows 98,
possibly back in the days of DOS v3.?,
and I learnt then to expect grief from a *.BAT script if it tried to alter itself.
I assumed the same was true now.

My more recent experience with XP is that the O.S. may complain that a file is in use when I try to delete it,
so I thought my old memories still applied.

Sorry

Regards
Alan
Quote from: ALAN_BR on September 25, 2010, 02:03:18 AM
I was remembering past experiences before CMD.EXE and before Windows 98,
possibly back in the days of DOS v3.?,
and I learnt then to expect grief from a *.BAT script if it tried to alter itself.
I assumed the same was true now.

My more recent experience with XP is that the O.S. may complain that a file is in use when I try to delete it,
so I thought my old memories still applied.

Sorry

Regards
Alan

Alan, this is just my 2 (euro) cents WORTH, but I don't really think you have any reason to apologise or say 'sorry' to anybody over this. You may have been inaccurate to say that a batch script is prevented from modifying or deleting itself, but you are certainly correct in your recollection that writing self-modifying code can be a risky business. A script that cuts the legs from under itself can lurch to DESTRUCTION. Having said that, self-modification is not always a bad thing. There is a good summary here

http://en.wikipedia.org/wiki/Self-modifying_code

As Wikipedia notes, "Because of the security implications of self-modifying code, all of the major operating systems  are careful to remove such vulnerabilities as they become known. The concern is typically not that programs will intentionally modify themselves, but that they could be maliciously changed by an exploit." and "Self-modifying code is also sometimes used by programs that do not want to reveal their presence — such as computer viruses and some shellcodes. Viruses and shellcodes that use self-modifying code mostly do this in combination with polymorphic code. Modifying a piece of running code is also used in certain attacks, such as buffer overflows."

In this regard, I am curious about the intentions of the OP.






Thank you Salmon

I remember the good old days when an anti-virus was pleased with itself if it could find and delete a suspect batch file.
The I.T. department chose one that excelled in deleting any batch file that had the command FORMAT C:\

I had problems with self modifying code.
I created a batch file called CD#.bat which LOOKED for arguments,
and in the absence of arguments would skip to the end and execute the final line,
which was something like
CD C:\z\z\z\z\z\z\z\z\z\z\z\z\z\z\z\z\z\z\
If it was given the argument '#' it would alter the final line to aim at whatever the current path was,
and the next day I immediately returned to yesterday's weird and wonderful directory with
CD#
Typically the new path was one extra 'z\'
I tried to design self modifying code but failed.
I finished with a "template" which CD#.bat duplicated as CD#.TMP
The template was identical to CD#.BAT excepting the final line was "CD " without any CRLF or CtrlZ,
then CD#.bat invoked
CD >> CD#.TMP
Then CD#.BAT deleted itself and renamed CD#.TMP as CD#.BAT
That at least was the result I wanted, but achieving the result involved the use of intermediate scripts.

The purpose of C:\z\z\z\z\z\z\z etc was that the first z\ held the first stage of a software product,
and successive z\ held the previous plus a new feature,
and the final z\ held the final product with all features.
If a feature was found to be broken it was easy to test its operation at each z\ to identify what broke it and then fix it.
This was when CVS etc version control was not available, and every man had to "roll his own".

I remember the aggravation when the I.T. dept changed to an anti-virus which deleted my master template.
It assumed that any *.BAT was up to no good and had to be deleted if it had a final command without a terminating CRLF

I remember the wonderful feeling of revenge when the IT department went round one night with a FAST application to detect any unlicensed software,
and the FAST application choked when it ENCOUNTERED my path with 80 or more 'z\' in a line.
(I forget what the character length was for a command.com command, but I took my path up to the limit)
This is a memory worth keeping ! !

Regards
Alan
272.

Solve : Batch File, moves only jpg?

Answer»

Hello all.
Been COMING to this site for YEARS for answers.

I do a lot of 4chan surfing an even have an auto download tool (beware it CARES less what it grabs lol)

so I have alot of mix file types I'd like a bat to send to their own folders.
I'm  using win7 (netbook)

I thought this would work for sure

echo on
move *.JPG C:\Users\******\Documents\Batch Testing 2\File Sort testing
pause

I'm getting " Cannot move multiple files to a single file "

I had a FEELING to try another drive so I plugged my flashdrive in an it worked fine.

does the C drive stop such ?
Try This


move *.JPG C:\Users\******\Documents\"Batch Testing 2"\"File Sort testing"\*.* Quote

C:\Users\******\Documents\Batch Testing 2\File Sort testing

Does this folder actually exist?
Quote from: Salmon Trout on September 23, 2010, 03:44:25 PM
Does this folder actually exist?


Yeah, the ***** is my name so I did that

Quote from: mat123 on September 23, 2010, 03:22:01 PM
Try This


move *.JPG C:\Users\******\Documents\"Batch Testing 2"\"File Sort testing"\*.*
nope. got this

C:\Users\******\Documents\Batch Testing 2\File Sort testing>move *.JPG C:\
Users\*******\Documents\"Batch Testing 2"\"File Sort testing"\*.*
The syntax of the command is incorrect.

C:\******\Documents\Batch Testing 2\File Sort testing>pause
Press any key to continue . . .The quotes need to go around the whole path

Code: [SELECT]move *.JPG "C:\Users\******\Documents\Batch Testing 2\File Sort testing"
this should do it
Graham Quote from: gpl on September 24, 2010, 12:32:52 AM
The quotes need to go around the whole path

Code: [Select]move *.JPG "C:\Users\******\Documents\Batch Testing 2\File Sort testing"
this should do it
Graham

Success
When I was added the path for the source it " syntax of the command is incorrect."
however when I ran it in the source folder it works fine.
273.

Solve : secure problem in ftp?

Answer»

Hello EVERYBODY,

I need your help. I have created a batch file that I make ftp to my server and I transfer some files, ONE time per month. I have scheduled this batch using the scheduled tasks of windows xp. The script works fine but I have a secure problem. The PASSWORD is visible!!

I give to you the commands that I use:

FTP -s:ftpwlk.txt env.meteo.noa.gr

this command open a txt file that contains the following details

"username"
"password"
binary
prompt n
cd stations/seli
mput C:\transfer.wlk\*.*
quit

There is any way to keep the password INVISIBLE?You could get your batch to prompt for the password, or protect the directory that the batch executes from so that only you can see itnowadays the secure way to transfer files is through SSH protocol. Try using SFTP/SCP for file transfer. You can set up passwordless keys so you don't have to hard code any password in your batch files.

274.

Solve : QBasic Help!?

Answer»

I needed help with a question for my class, QBasic Programming. This is the question.

If you have the book its on page 118 number 4

4. Write a program to LIST several ACTIVITIES and the number of calories expended during 15, 30, and 60 minutes of each activity. Use the following Data:

Activity             Calories Burned per Minute
Sleeping           2.3
Jogging            15.0
Sitting              1.7

Use READ and DATA statements to place the data in variables. Then use commas to space the output so that is looks similar to the following:

Activity          15 Minutes     30 Minutes     60 Minutes
Sleeping         xxx.xx            xxx.xx            xxx.xx
Jogging          xxx.xx            xxx.xx            xxx.xx
Sitting            xxx.xx            xxx.xx            xxx.xxwow, didn't know anyone would still WANT to learn QBasic.  I hope its a free class you are taking, if not, its certainly not worth the school fees you are paying for.well this class i am taking is free and it is just a beginning to comp progQbasic is out of date. Try using a better programming LANGUAGE (eg Python), where you can learn about advance data structures like arrays/hashes/collections and much more.

Code: [Select]print "%-15s%-15s%-15s%-15s" %("Activity","15 min","30 min","60 min")
f=open("file")
f.readline() # get first line
for line in f:
   act, t=line.rstrip().split()
   print "%-15s%-15s%-15s%-15s" %( act,float(t)*15,float(t)*30,float(t)*60 )
f.close()

output

Code: [Select]C:\test>python test.py
Activity       15 min         30 min         60 min
Sleeping       34.5           69.0           138.0
Jogging        225.0          450.0          900.0
Sitting        25.5           51.0           102.0


If you insist on something from M$, try learning vbscript instead. www.network54.com/forum/648955/

275.

Solve : Convert Tiff file only if condition applies?

Answer»

Hello fellow msdos coders, I wish I could do this with python or some other uncluttered language, but it has to be dos... I thank you in advance for any input.

Here's the scenario.

I have a large number of Tiff image files in folders and subfolders, and I need to convert them to a different color profile ONLY if they HAPPEN to be with the 'wrong' profile.

I'm CONFUSED as to how the 'for' works, i'd like to get 'secondary' action in my for loop, but can't figure out how

Code: [Select]for /r %%a in (*.tif) do (identify -verbose "%%~FA" >> t.txt)

will print some info (using 'imagemagick') and somewhere in there should (or shouldn't) be a line with "ADOBE RGB" in it

so I should add

Code: [Select]& if find "Adobe RGB" < (output of the 'identify' above)

or something that looks like it

then according to the result

do this:

Code: [Select]convert -profile AdobeRGB1998.icc -profile sRGB.icm %%a sRGB_%%~na.tif

Which is the only bit that I know works =)

If you can help me stitch the whole thing together, I'll give you a million internet hugs =)

Thanks and have a good day

BernieYou could pipe the output of identify to find.exe and use the && (success) operator to decide whether to run convert

Code: [Select]for /r %%a in (*.tif) do identify -verbose "%%~fa" | find "Adobe RGB" && convert -profile AdobeRGB1998.icc -profile sRGB.icm "%%a" "sRGB_%%~na.tif" Quote from: Salmon Trout on September 28, 2010, 11:29:06 AM

You could pipe the output of identify to find.exe and use the && (success) operator to decide whether to run convert

Code: [Select]for /r %%a in (*.tif) do identify -verbose "%%~fa" | find "Adobe RGB" && convert -profile AdobeRGB1998.icc -profile sRGB.icm "%%a" "sRGB_%%~na.tif"

thanks, it does the trick!Ahah, so I have a little more WORK on that script, right now it works, but instead of using a prefix, I'd like to copy my newly converted files into a subfolder, unfortunately it gets processed as well, resulting in a neverending loop!

Any ideas?

Code: [Select]for /r %%a in (*.tif) do identify -verbose "%%~fa" | find "Adobe RGB (1998)" &&  mkdir "%%~pa/sRGB" && convert -profile AdobeRGB1998.icc -profile sRGB.icm "%%a" "%%~pa/sRGB/%%~na.tif"
Copy them into a folder outside the tree being walked by FOR /R, or instead of FOR /R you can use FOR /F to parse the output of 'dir /b /s *.tif', use %%~pa to identify those tifs not in the converted folder, which you convert and move.



Quote
I'd like to copy my newly converted files into a subfolder, unfortunately it gets processed as well, resulting in a neverending loop!

But don't the converted files have a different profile? How do they get processed twice?
276.

Solve : emails with batch files?

Answer»

i need to send emails with the help of using batch files. how can i send the mails with batch files.Have you tried the search function on this site, I know it has been answered beforeFor use in batch files you can use Blat or MailSend.

If you have WINDOWS, you can use any of the above or VBScript (already installed) or any other script language you may have downloaded and installed.

If you have Windows 7, you can use any of the above or Powershell (Powershell may have to be activated)

You are limited only by your imagination.

Good luck. I am using mailsend to send out pages to people from a batch file.   It should work for what you want to do. Code: [Select]echo off
cd folderexample
for %%* in (.) do set VAR=%%~n*
for /f %%a in ('time/t') do set vartime=%%a
set body=-body "hello"
set [email protected]
set [email protected]
set subj=-s "Test. FTP.%var%. New Files. %vartime%"
set server=-server smtp.example.com
set user=-u userexample
set pass= -pw passwordexample
C:\VISHU %0 -f %from% -b %to% %subj% %body% %server% %user% %pass%

I hope this will help you.
if do click on thanksthis is what i am using to send alerts.  Download the latest version of mailsend and put it in your windows/system32 dir
this is the command.  Its all one line but broken up here due to cut and paste.  I need to use port 2525 due to my ISP.  Change it to whatever works for you. 

mailsend -d your domain -smtp your SMTP server -port 2525 -starttls -v -f from address to show on email +CC +bc -auth-login -user user on SMTP server -pass "user password" -t to:email address -sub "subject" -M "MESSAGE"




good luck

277.

Solve : Returning the date and time on file?

Answer»

I picked up this CODE from Salmon Trout from another post.  When I look at files on my desktop the date and time are echoed fine.  When I TRY to look at files on another drive or a server I get no echo at all.

Any thoughts?

echo off
for /f "delims=" %%A in ( 'dir /b /a-d /od c\:docume~1\[username]\desktop\[filename]' ) do (
   set fdate=%%~tA
      )
echo %fdate%I believe the ~t variable modifier only works on local drives. What HAPPENS if you try to get a full DIR listing (not using /b) of the folder? I mean this style of listing...

Code: [Select]Volume in drive C is Win07
 Volume Serial Number is E4DB-A92A

 Directory of C:\

24/09/2010  06:26 PM             1,024 .rnd
19/06/2010  03:16 PM             1,414 backup.log
28/03/2010  10:46 PM               956 dir.txt
06/10/2010  05:35 PM     3,169,705,984 hiberfil.sys
02/01/2010  08:03 PM            57,310 Logon001.jpg
14/03/2010  09:52 PM             1,106 makespecialfolders.bat
03/03/2007  05:44 PM            15,658 mike.jpg
28/03/2010  10:45 PM               870 mike.jpg.lnk
06/10/2010  05:35 PM       314,572,800 pagefile.sys
13/07/2010  06:26 PM       111,562,752 PM11_Pers_full_ea_x64.msi
29/07/2010  10:47 PM                79 whatever.scf
              12 File(s)  3,595,930,401 bytes
               0 Dir(s)  72,403,623,936 bytes freeWhen I get the full listing I have the file names and dates and TIMES as you have shown.  When I use the /b switch I just get the names. Quote

When I get the full listing I have the file names and dates and times as you have shown.

If you can show me (by copy and paste) the format of such a listing I can tell you how to extract the date and time information. I need to see this to know the character positions. It looks from your code as if you require the date and time of the last (LATEST) file in the folder.

Here it is

 Volume in drive C has no label.
 Volume Serial Number is 984C-4C03

 Directory of C:\D_Drive\workspaces\0102\batch\gisdb\wad

10/07/2010  10:39 AM              .
10/07/2010  10:39 AM              ..
10/28/2009  03:34 PM               193 0102bsav.addr
09/16/2007  03:32 PM               193 0102bsav.bld
08/10/2010  11:30 AM         1,543,341 0102bsav.dbf
08/10/2010  11:30 AM                 2 0102bsav.lab
10/28/2009  03:34 PM               193 0102bsav.sub
10/05/2010  08:48 AM            50,684 0102ds.addr
10/28/2009  01:33 PM               288 0102ds.alt
09/16/2007  03:32 PM               193 0102ds.bld
10/06/2010  12:03 PM         1,234,550 0102ds.dbf
10/06/2010  12:03 PM                 2 0102ds.lab
10/06/2010  11:40 AM         9,278,082 0102ds.seq
10/01/2010  12:50 PM            19,634 0102ds.sub
10/07/2010  10:39 AM                 0 myfile.txt
              13 File(s)     12,127,355 bytes
               2 Dir(s)  10,652,610,560 bytes free Code: [Select]
echo off
setlocal enabledelayedexpansion
set dirname="S:\Test"
set dirswitches=/a-d /od
for /f "tokens=1-4* delims= " %%A in ('dir %dirswitches% "%dirname%" ^| findstr /v "File(s) Dir(s) Volume Directory"') do (
    set fdate=%%A
    set ftime=%%B
    set AM-PM=%%C
    set fname=%%E
    )
echo File date %fdate%
echo File time %ftime% %AM-PM%
echo File name %fname%   
278.

Solve : User-input in PC-DOS?

Answer»

Hello. I SOMETIMES boot my computer from a live PC-DOS 7.1 CD, but I've noticed that I can't USE 'SET /P' to take input from the user. When I TRY using 'CHOICE' it just says "Bad command or file name.' How can I do this?

Please HELP!
Thanks,
phillid

279.

Solve : ethernet ipaddress keeps changing and won't let me on internet?

Answer»

RIght now I am using wireless on my WIndows XP. THis started happening recently when I switched over to RR cable from dial-up. THis is a 3 yr OLD Toshiba laptop. I have spent the last 4 weeks dealing with techs from both companies(RR & Toshiba) and the problem is still erratic. Sometimes it works and sometimes it doesn't. I have done all of their suggestions like going thru the ipconfig---release---and renew stuff. I went thru the one of taking out the battery, shutting it off, pushing the off swicth for 15 seconds waiting and putting it all back together. I tried a different Ethernet cord and it worked for about three days. I also did the RR thing of disconnecting the laptop power source/modem and turning it back on after counting the required number of seconds. I was about to try black magic when I ran across this site (I was learning about external commands). Retirement sucks when I cannot use my internet. Help. Please.Road Runner, not so beep beep?   

Does the RR cable run through the telephone exchange?
I assume the 'modem' is actually a wired router?

I SUGGEST first looking under your router admin gateway.
To go to that your'll need to type '//' (without quotes) and the router's IP address in your web-browser and enter your admin details. Read the manual that came with the router if stuck.

Under connection details, you should see 'Uptime', 'Bandwidth (Up/Down)', etc...

Find 'Line Attenuation (Up/Down)' and 'SN Margin', ensure the [dB] doesn't change a lot when refreshing that page.

You might also want to check:
Loss of Signal / Power (Local/Remote)
FEC, CRC, and HEC Errors (Up/Down)

Depending on your router model, they should be all on the same page. Post the results here if possible and note any continous changes on refreshing that page.


If you have a noisy line, another way of testing this is pick up the phone and dial just one number to clear the dial tone and LISTEN for STATIC or noise.  Noise on the line hugely decreases internet performancee and it get's too much, the line will cut and attempt to reconnect with another IP address. This might be your issue?

280.

Solve : mass rename in MS-DOS?

Answer»
I have files existing with same names in the folders with date as display below

Code: [Select]

C:\2010-09-10   <==== folder
   arr1.jpg
   arr2.jpg
   arr3.jpg
   arr4.jpg

c:\2010-09-09 <==== folder
   arr1.jpg
   arr2.jpg

c:\2010-09-08    <==== folder
   arr2.jpg
   arr3.jpg
   arr4.jpg
   arr5.jpg
   arr8.jpg
   arr9.jpg
   arr10.jpg
   arr11.jpg

 c:\2010-09-07 <==== folder
   arr2.jpg
   arr3.jpg
   arr4.jpg
   arr10.jpg
   arr11.jpg

c:\2010-09-06 <==== folder
   arr9.jpg
   arr10.jpg
   arr11.jpg

c:\2010-09-05 <==== folder
   arr2.jpg
   arr3.jpg
   arr4.jpg
   arr5.jpg
   arr6.jpg
   arr7.jpg
   arr8.jpg

c:\2010-09-04 <==== folder
   arr2.jpg
   arr3.jpg
   arr5.jpg
   arr6.jpg
   arr7.jpg
   arr8.jpg
   arr9.jpg
   arr10.jpg
   arr11.jpg

c:\2010-09-03 <==== folder
  arr2.jpg
  arr3.jpg
  arr4.jpg
  arr5.jpg
  arr6.jpg
  arr7.jpg
  arr10.jpg
  arr11.jpg

c:\2010-09-02   <==== folder
 arr2.jpg
 arr3.jpg
 arr4.jpg
 arr5.jpg
 arr6.jpg
 arr7.jpg
 arr8.jpg
 arr11.jpg

c:\2010-09-01  <==== folder
 arr2.jpg
 arr3.jpg
 arr4.jpg



I would like to rename those files as _.jpg. and move all the files in single folder CALLED All_pics
The SrNo is a continous running number serial number.

Code: [Select]C:\All_pics\
   2010-09-10_54.jpg   
   2010-09-10_55.jpg   
   2010-09-10_56.jpg 
   2010-09-10_57.jpg 
   
   2010-09-09_52.jpg 
   2010-09-09_53.jpg 
   2010-09-08_44.jpg 
   
   2010-09-08_45.jpg 
   2010-09-08_46.jpg 
   2010-09-08_47.jpg 
   2010-09-08_48.jpg 
   2010-09-08_49.jpg 
   2010-09-08_50.jpg 
   2010-09-08_51.jpg 
   
   2010-09-07_39.jpg 
   2010-09-07_40.jpg 
   2010-09-07_41.jpg 
   2010-09-07_42.jpg 
   2010-09-07_43.jpg 
   
   2010-09-06_36.jpg 
   2010-09-06_37.jpg 
   2010-09-06_38.jpg 
   2010-09-05_29.jpg   
   2010-09-05_30.jpg   
   2010-09-05_31.jpg   
   2010-09-05_32.jpg   
   2010-09-05_33.jpg   
   2010-09-05_34.jpg   
   2010-09-05_35.jpg   
   
   2010-09-04_20.jpg   
   2010-09-04_21.jpg   
   2010-09-04_22.jpg   
   2010-09-04_23.jpg   
   2010-09-04_24.jpg   
   2010-09-04_25.jpg   
   2010-09-04_26.jpg   
   2010-09-04_27.jpg   
   2010-09-04_28.jpg   
   
   2010-09-03_12.jpg   
   2010-09-03_13.jpg   
   2010-09-03_14.jpg   
   2010-09-03_15.jpg   
   2010-09-03_16.jpg   
   2010-09-03_17.jpg   
   2010-09-03_18.jpg   
   2010-09-03_19.jpg   
   
   2010-09-02_04.jpg   
   2010-09-02_05.jpg   
   2010-09-02_06.jpg   
   2010-09-02_07.jpg   
   2010-09-02_08.jpg   
   2010-09-02_09.jpg   
   2010-09-02_10.jpg   
   2010-09-02_11.jpg   
   
   2010-09-01_01.jpg 
   2010-09-01_02.jpg
   2010-09-01_03.jpg

 Which version of MS-DOS are you running?  Advice given may alter with the version.

However, if you mean the Command Shell in Windows try the following:

Code: [Select]ECHO off
cls
setlocal enabledelayedexpansion

echo y | del all-pics\*.*>nul

set nbr=1
if not exist all-pics\ md all-pics\

for /F "tokens=*" %%1 in ('dir /ad /b 2010*') do (
    set folder=%%1

    for /f "tokens=*" %%A in ('dir /b "!folder!"') do (
        if !nbr! LSS 10 set nbr=0!nbr!
        copy !folder!\%%A all-pics\!folder!_!nbr!.jpg>nul
        if !nbr! lss 10 set nbr=!nbr:~-1!
        set /a nbr+=1
        )
)

281.

Solve : Variables in For Loops (And If statements)?

Answer»

It seems Variables I declare within a FOR loops (or if statements) are getting FORGOTTEN about RIGHT away. The %%A of the FOR head works fine throughout the loop but a simple

SET TEST=%%A

will vanish...

Any idea why?Please show your script.He's deleted his acoount; I expect he found out about DELAYED expansion.

282.

Solve : %PATH% - Environment Looking for a PATH?

Answer»

Looking for a way to pull a directory out of the PATH environmental VARIABLE. Guess I'm more so looking for the drive letter. I know my path will CONTAIN \vision\bin ... I was thinking I could do a FOR loop but I'm just not getting it at midnight. Help is appreciated.

Code: [Select]for /F "tokens=1-26 delims=;" %%a in ('echo %PATH% ^ FIND /I "\vision\bin"') do set direct=%%a
I figured I would use delims=; to separate each path out, but then again maybe that is my problem that when I set direct %%a isn't my path? I'm not sure.

Nevermind ... I got something to work.

Code: [Select]ECHO off
setlocal enabledelayedexpansion
 for %%G in ("%PATH:;=" "%") do (
    echo %%G | find /I "\vision\bin" >nul
    if !errorlevel! EQU 0 set direct=%%G
 )
setlocal disabledelayedexpansion
if "%direct%"=="" ECHO direct equals nothing & pause
set direct=%direct:"=%
set direct=%direct:~0,9%
echo "%direct%"
Pause

283.

Solve : Conditional sentence in MS-DOS?

Answer»

Hi, I'm not an expert in MS-DOS, that's the reason of my question. How could I PUT a conditional question in a DOS batch?

For example:

Would you like to execute the next process? Y/N

Best regards.several options; the "easiest" is to use pause:

Code: [Select]ECHO OFF
pause To process the next item, press any key. To Cancel, Press Control+Break.

REM etc..

or, use CHOICE:

Code: [Select]ECHO OFF
REM CLEAR DONEXT:
set DONEXT=
:RECHOICE
choice Would you like to execute the next process?
IF ERRORLEVEL==2 GOTO PRESSEDN
IF ERRORLEVEL==1 GOTO PRESSEDY
ECHO Please Enter Y OR N.
GOTO RECHOICE
:PRESSEDN
REM N was pressed in CHOICE.
SET DONEXT=N
GOTO ENDING
:PRESSEDY
REM Y was pressed
SET DONEXT=Y
:ENDING

REM return to caller.


I wrote the second one with the intent that it may be used as "module" SORT of of fashion; that is, it may be called from multiple locations in the same batch file. You can of course paste this in if there is only a single location, but otherwise, you would need to make it a new BAT file- say, "DOCHOICE.BAT" or something.

Then, in the main batch, you would simply do:

Code: [Select]REM check if we should execute the next process...
DOCHOICE
if %DONEXT%==Y GOTO GOTONEXT
if %DONEXT%==N GOTO NONEXT

You would of course define the GOTONEXT label to continue the process, and NONEXT to abort the procedure or display a warning like "not all PROCESSES run" or whatever, depending on your use case.

You'll note something particularly rare these days, is that I was able to provide a batch that actually used only DOS features, and didn't try to suggest "YOU CAN USE SET /P" or something stupid like that. That sort of annoys me when I see folks asking for help with DOS and then self-proclaimed "Batch masters" coming in with their advice that requires NT extensions. This is especially annoying since the original poster probably doesn't even know about these extensions and therefore will try to follow their advice. I've seen 3 PAGE threads here where poor folks are led on a wild-goose chase while the "batch master" tries to figure out why set /p doesn't work.

I'll SHUT up now.Thanks a Lot!

284.

Solve : How to copy files to two words name folder?

Answer»

Problem is:
 when I tried to copy files to c:/Program Files/Folder. got the error message as
E:\SomeDirectory\Patches>copy *.* C:\Program Files\Destination\
The syntax of the COMMAND is incorrect.

CODE:
Code: [Select]cd E:\SomeDirectory\Patches
copy *.* %VALUE%I believe it because of space between Program Files.
In to the other destination all files were copied ok.
How can I solve this problem?I found it!
If you using path to TWO word name folder just put it between " "
In my case it looks like
Code: [Select]"C:\Program Files\iWay60\"

285.

Solve : Getting duration of .wmv files using: dir >filelist.txt?

Answer»

Hi there,

I can see the "duration" (length of the video) for each of our .wmv files in windows explorer by turning on that column, but can't find how to GET that into a text file. We have hundreds and hundreds of files that we need the duration for, and obviously we don't want to have to type it all in by hand when the information is displayed right there in front of us.

I've tried .js as well, but am stumped. My .bat file currently looks like this:

dir /n /a /-p /o:gen >filelisting.txt

This allows me to capture most of the information I need and port it over to our database, but lacks the duration info.

Note that I did come across something called "verbose" (/v) that is supposed to list more information, but the batch file fails when I add it in, and I'm not even sure that would show the duration.

Help? The information you see in Windows Explorer about multimedia files (duration, bitrate, etc) is not available to the command prompt, certainly not via DIR. There is no /V switch for DIR.

But you can use ffmpeg to provide multimedia information, and find to isolate the line with the duration information.

http://www.ffmpeg.org/

Example 1. Use ffmpeg with the -i option to get information about a file

Code: [Select]C:\Users\Public\VIDEOS\Sample Videos>ffmpeg -i wildlife.wmv
FFmpeg version SVN-r23418, Copyright (c) 2000-2010 the FFmpeg developers
  built on Jun  2 2010 04:12:01 with gcc 4.4.2
  configuration: --target-os=mingw32 --enable-runtime-cpudetect --enable-avisynth --enable-gpl --enable-version3 --enable-bzlib --enable-libgsm --enable-libfaad
 --enable-pthreads --enable-libvorbis --enable-libtheora --enable-libspeex --enable-libmp3lame --enable-libopenjpeg --enable-libxvid --enable-libschroedinger --
enable-libx264 --extra-libs='-lx264 -lpthread' --enable-libopencore_amrwb --enable-libopencore_amrnb --enable-librtmp --extra-libs='-lrtmp -lssl -lcrypto -lws2_
32 -lgdi32 -lwinmm -lcrypt32 -lz' --arch=x86 --cross-prefix=i686-mingw32- --cc='ccache i686-mingw32-gcc' --enable-memalign-hack
  libavutil     50.16. 0 / 50.16. 0
  libavcodec    52.72. 1 / 52.72. 1
  libavformat   52.67. 0 / 52.67. 0
  libavdevice   52. 2. 0 / 52. 2. 0
  libavfilter    1.20. 0 /  1.20. 0
  libswscale     0.11. 0 /  0.11. 0

Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 29.97 (30000/1001)
Input #0, asf, from 'wildlife.wmv':
  Metadata:
    SfOriginalFPS   : 299
    WMFSDKVersion   : 11.0.6001.7000
    WMFSDKNeeded    : 0.0.0.0000
    IsVBR           : 0
    title           : Wildlife in HD
    author          :
    copyright       : ┬® 2008 Microsoft Corporation
    comment         : Footage: Small World Productions, Inc; Tourism New Zealand | Producer: Gary F. Spradling | Music: Steve Ball
  Duration: 00:00:30.09, start: 8.000000, bitrate: 6977 kb/s
    Stream #0.0: Audio: wmav2, 44100 Hz, 2 channels, s16, 192 kb/s
    Stream #0.1: Video: vc1, yuv420p, 1280x720, 29.97 tbr, 1k tbn, 1k tbc
At least one output file must be specified
Example 2. Note that ffmpeg outputs info text to stderr so to pipe to find we need to redirect stderr to stdout using 2>&1

Code: [Select]C:\Users\Public\Videos\Sample Videos>ffmpeg -i wildlife.wmv 2>&1 | find "Duration"
  Duration: 00:00:30.09, start: 8.000000, bitrate: 6977 kb/s
You can redirect the information to a file, and use standard batch or vbscript methods to process the information.








vbscript
Code: [Select]Set objFS = CreateObject("Scripting.FileSystemObject")
Set objPlayer = createobject("wmplayer.ocx.7")
strFolder="c:\videos"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
If objFS.GetExtensionName(strFile) = "mp3" Then    
strFileName = strFile.Path
WScript.Echo objPlayer.mediaCollection.add(strFileName).duration
End If
NEXT
objPlayer.close

Code: [Select]c:\test> cscript //nologo myscript.vbs
Does that work for .wmv's or just .mp3's?why don't you try it out? Quote from: Helpmeh on September 15, 2010, 08:55:13 PM

Does that work for .wmv's or just .mp3's?

Yes. One would need to change the "if" test but that's not difficult at all. Quote from: ghostdog74 on September 15, 2010, 07:22:26 PM
vbscript
Code: [Select]Set objFS = CreateObject("Scripting.FileSystemObject")
Set objPlayer = createobject("wmplayer.ocx.7")
strFolder="c:\videos"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
If objFS.GetExtensionName(strFile) = "mp3" Then    
strFileName = strFile.Path
WScript.Echo objPlayer.mediaCollection.add(strFileName).duration
End If
Next
objPlayer.close

Code: [Select]c:\test> cscript //nologo myscript.vbs


is it possible in your opinion to use that code in an asp vbscript PAGE?

I try it changing the  "WScript.Echo objPlayer.mediaCollection.add(strFileName).duration" line
in Response.write(objPlayer.mediaCollection.add(strFileName).duration), but doesn't work...


286.

Solve : Batch file execution control?

Answer»

What KINDS of limits can be put on opening batch FILES? I want to MAKE a .BAT that can ONLY be opened by another, SPECIFIED .BAT file. I don't even want the file to be readable from notepad. How would I do this? And is it possible to limit whether a file will open in some programs, but not others? Quote

I want to make a .BAT that can ONLY be opened by another, SPECIFIED .BAT file.

Nope

Quote
I don't even want the file to be readable from notepad.

Nope

Quote
And is it possible to limit whether a file will open in some programs, but not others?

And nopeWell shoot! It was worth a shot...

Thanks!
kyle_engineer
287.

Solve : Trying to make a really simple batch file and failing?

Answer»

Like the subject says I'm having a hard time understanding the syntax of batch files. This one in particular from what I understand is quite simple but I'm having a *censored* of a time figuring it out. I'm just trying to turn off the echo of all commands in the batch program, set the background color to bright white, and the foreground color to black, specify a setting in the Windows environment for the DIR command so it displays directories and files one SCREEN at a time, in order by filename and then clear the screen.

Any pointers?Unfortunately, you worded your question in such a way that it looks exactly like a homework assignment. Homework assignments do a number of things, including TESTING, for the teacher's information, your understanding of the course material you have already been exposed to and your ability to perform research.  If we do this work for you, the teacher will think you are having no PROBLEMS and you will never get the remedial help you so obviously NEED. My advice is to study the materials given you by your teacher. If you still do not understand this (very) simple TASK, consult your teacher for guidance.


288.

Solve : How to move files based on file size with batch file??

Answer»

I need to check 10 different Source directories for files and move them to 10 different DESTINATION directories. However files over 50Mb I need to move to a BigFile directory and rename the EXTENSION to *.big. I'm new/rusty to batch files but I've created the following script that I can't SEEM to get working correctly. I'm using it in a windows environment.



echo on

setlocal

set /p directory1=D:\receivingdir\2.16.840.1.113883.3.105.102

set /a size=52428800

set /p newdirectory1=D:\processingdir\Sources\2.16.840.1.113883.3.105.102\In

set /p newdirectory2=D:\BigFileTransport

for %%q in %directory1% do if %%~zq lss %size% move %%q %newdirectory1%


for %%q in %directory1% do if %%~zq geq %size% move %%q %newdirectory2%

pause


Any ideas?Lose the /p switch from SET. For details of usage of SET command, type SET /? at the prompt.

If any filenames are likely to have spaces you should use quotes

e.g.

Code: [Select]move "%%q" %newdirectory1%
FOR syntax needs correction

Code: [Select]for /f "delims=" %%q in ( ' dir /b /a-d "%directory1%\*.*" ' ) do if %%~zq lss %size% move "%%q" %newdirectory1%

THANKS Salmon!

289.

Solve : Combine Check Disk and Defrag into one Bat file, and get no error messages?

Answer»

I've been getting these error MESSAGES, using Scheduled Tasks to do Check Disk and Defrag on my two HARD drives:

5/18/10 it did not Defrag C:, got exit code of 0x6

9/21/10 It did not Check Disk D:, cannot lock current drive, volume dismounted, all opened handles to this volume are now invalid

I think I just need to disable some services, then it will work.  Everything I've figured out is here, I think I'm close:

http://www.codeproject.com/Questions/117564/DOS-commmands-to-disable-re-enable-non-MS-Services.aspx?display=Print

This is what I have that needs to be modified somehow.  The code just flashes on the screen.  Thank you for your input.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

sc config avg9wd start= disabled
sc config CTAudSvcService start= disabled
sc config nvsvc start= disabled

ECHO y|CHKDSK D: /X/R
ECHO y|CHKDSK C: /R

C:\WINDOWS\system32\defrag.exe d: -v>"c:\Documents and Settings\Administrator\Desktop\defrag d.txt"
C:\WINDOWS\system32\defrag.exe c: -v>"c:\Documents and Settings\Administrator\Desktop\defrag c.txt"

sc config avg9wd start= auto
sc config CTAudSvcService start= auto
sc config nvsvc start= auto

SHUTDOWN -rI PUT my conclusion here at the bottom of this page.

http://www.codeproject.com/Questions/117564/DOS-commmands-to-disable-re-enable-non-MS-Services.aspx

It does not appear to me that a DOS command can disable some Services

******************************************************************

Control Panel \ Network Connections \ [right-click] Local Area Connection 5 \ Disable

Start \ Run \ msconfig \
Services tab \ [check] Hide All Microsoft Services \ Disable All \ Apply
Startup tab \ Disable All \ Apply
Close \ Restart

Then let Scheduled Tasks run the following bat file at 1:00 AM, on the third Tuesday of every month, view the RESULTS in the AM.

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

C:\WINDOWS\system32\defrag.exe c: -v>"c:\Documents and Settings\Administrator\Desktop\defrag c.txt"
C:\WINDOWS\system32\defrag.exe d: -v>"c:\Documents and Settings\Administrator\Desktop\defrag d.txt"

ECHO y|CHKDSK C: /R
ECHO y|CHKDSK D: /X/R

SHUTDOWN -r

290.

Solve : How to time stamp the text file??

Answer»

Hi Friend,

Is there any possiblity to time stamp the text file.

For e.g.

I am having text file named as a.TXT.
I need to rename this file with date and time b_08062008_10AM.txt

Please help me to resolve this issue.

Thanks,
Vinoth Sorry, but the Ren(rename) command DOESNT accept variables so if you tried to rename a.txt to %DATE%.txt, you would recieve an error message saying "The syntax of the command is incorrect" but you can post a timestamp in the txt file. I provided the batch program as a TXT file, open it and Save it as a BAT file. Once again, Im sorry but i hope this helps your problem.   



[recovering disk space -- attachment deleted by admin]on my computer ren works with variablesIt does on mine. The reason for macdad's error is that he does not realise that the date & time variables contains / and : characters that are illegal in a file NAME.

so you can remove them

Code: [Select]S:\>ren hello.txt hello-%date:/=-%-%time::=-%.txt

S:\>DIR hello*
 Volume in drive S is USBHD
 Volume Serial Number is 2C51-AA7F

 Directory of S:\

06/08/2008  17:03                 8 hello-06-08-2008-17-08-39.28.txt

Dias i separated the backslashes from the date and time variables in the batch program i included in this and the earlier post. but yes when i tried it on command prompt(not in a batch file) i forgot to seperate the backslashes.

[recovering disk space -- attachment deleted by admin]Thanks guys , this is just the solutution I was looking for.

I run sofware updates most days and the setup program overwrites the install log.  I could never check if the LAST 5 or 10 updates were all sucessful, just the last update. Now I can copy the log file to another folder with a timestamp in the filename ! Brilliant.

291.

Solve : check for double quote in a string?

Answer»

Is it POSSIBLE to check for a double quote at the END of a string?

Reason is, I've created a batch file where users drag and DROP a folder onto the batch file and it uses that as a parameter.

If the folder has a space it encloses it in double quotes, I can strip them off with the SET COMMAND...but if there is no space then it doesn't enclose it in quotes.

Code: [Select]set StartFolder=%1
if '%StartFolder%==' goto NoFolder
set tmpstr=%StartFolder:~-1%

rem *** If last char is double quote, strip them off - '" = Single the double quote***
if '%tmpstr% == '" set StartFolder=%StartFolder:~1,-1%

set tmpstr=%StartFolder:~-1%
rem *** If last char is not backslash, ADD one ***
if '%tmpstr% NEQ '\ set StartFolder=%StartFolder%\


How can I check if the parameter has quotes?Solved it by adding a ^ before the double quote...

Code: [Select]set StartFolder=%1
if '%StartFolder%==' goto NoFolder
set tmpstr=%StartFolder:~-1%

rem *** If last char is double quote, strip them off - '" = Single the double quote***
if '^%tmpstr% == '^" set StartFolder=%StartFolder:~1,-1%

set tmpstr=%StartFolder:~-1%
rem *** If last char is not backslash, add one ***
if '%tmpstr% NEQ '\ set StartFolder=%StartFolder%\
 You do know that the tilde variable modifier strips off any surrounding quotes from parameter strings?

If %1 is a passed parameter string, then %~1 is that same string but without any surrounding double quotes. (If no quotes are present then %1 and %~1 are identical)

For full details of variable modifiers see the FOR documentation e.g. by typing FOR /? at the prompt.




292.

Solve : Creating a batch file that copies sub-folders?

Answer»

I have a batch file that reads
Copy TEMPORARY\%1  Directory 1
Copy temporary\%1  Directory 2
and so on
for 65 directories (!)

What this does is to take ALL the FILES in the folder called temporary and copy them to Directory 1 and to Directory 2 and so on.

Now, the complication is that the folder called temporary has a subdirectory called Documents with 20-25 files in it.
I wiuld like to know what the syntax is for
a) MD New Directory in Directory 1 and in 2 and so on
b) copy the 20-25 files into it
and - hopefully - all that with ONE command.

Any ideas?



Thanks!




I would go with XCOPY or ROBOCOPY, in your batch file. QUOTE from: Mute on October 19, 2010, 12:03:26 AM

I would go with XCOPY or ROBOCOPY, in your batch file.

http://www.mydigitallife.info/2007/05/07/robocopy-syntax-command-line-switches-and-examples/

Ducks that fly upside down quake up.
293.

Solve : copy emails?

Answer»

i want to create a batch file that will copy my emials and put them in TH foler they belong can you help?thanks ron Quote from: ron57 on October 18, 2010, 02:15:38 AM

i want to create a batch file that will copy my emials and put them in th foler they belong can you help?thanks ron

What email client are you using? How do you determine which email goes to what folder? I doubt you can do this with batch code.

Need more info.  i am using 9.1 aol thanks ronAOL is proprietary and I could not find an ActiveX SCRIPT Control which would be needed for scripting. You might be able to USE the sendkeys method in VBScript, but it can be haphazard and unreliable. I don't have AOL installed, so I won't be much help here.

AOL Explorer and IE7 are similar, so you might be able to script the web side of AOL (that might be a major project and time consuming).

For future reference, can you not setup RULES that dictate where incoming mail should be delivered? If incoming mail COMES from PersonA, send it to FolderA and if incoming mail comes from PersonB, send it to FolderB.

If you need further help get back to us.

Good luck.  this is the probleblem i have subscired to many ad exchanges.i get mail from them all to give me points for advertising. i sepratley i need a batch file that saves the emails to the folders i create in aol 9.1?thanks roncan i just copy the emails to a misc folder then sort them out from there?can you send me a batch file that will copy those emails to any folder?thanks ron Quote from: ron57 on October 19, 2010, 07:56:28 AM
can i just copy the emails to a misc folder then sort them out from there?can you send me a batch file that will copy those emails to any folder?thanks ron

It's not that simple. Without a script control, you cannot create an AOL object. Without the object you cannot script the program.  My guess is that you'll need to do this manually within the AOL environment.

You should try Google. I found nothing useful, but you might. If you're referring to copying to an external folder, you might find some 3rd party software that can do extraction or export operations.

Good luck.
294.

Solve : Changing the date when you run a program?

Answer»

Is there a WAY that I can CHANGE the date on my PC when I run a certain program?

For example, I want to run this COMMAND "date 01-01-2009" whenever I launch one of my applications.

Is there a way I can ATTACH this to the shortcut of my program.Is this to defeat a trial PERIOD?

295.

Solve : How do I run an .exe from CScript without creating a separate window??

Answer»

All the examples I have found are like this:

Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "cmd /K CD C:\ & 7z a E:\ZipOut1 C:\TempBase"
Set oShell = Nothing

I would like to run several 7z commands in succession using CSCRIPT, but without creating a separate window for each one, and ideally without creating any new windows at all.
Code: [Select]
wscript.echo "Running 3 7zip operations"
wscript.echo
Run "7z a s:\ZipOut1 s:\Test-777\*"
Run "7z a s:\ZipOut2 s:\Test-777\*"
Run "7z a s:\ZipOut3 s:\Test-777\*"
wscript.echo
wscript.echo "Completed 7z operations"
wscript.echo
wscript.echo "Files produced:"
wscript.echo
Run "cmd /c dir s:\Zipout*"
wscript.echo
wscript.echo "Done"

' Runs an external program and pipes its output to
' the StdOut and StdErr streams of the current script.
' Returns the exit code of the external program.
Function Run (ByVal cmd)
Dim sh: Set sh = CreateObject("WScript.Shell")
Dim wsx: Set wsx = Sh.Exec(cmd)
Do
   Dim Status: Status = wsx.Status
   WScript.StdOut.Write wsx.StdOut.ReadAll()
   WScript.StdErr.Write wsx.StdErr.ReadAll()
   If Status <> 0 Then Exit Do
   WScript.Sleep 10
   Loop
Run = wsx.ExitCode
End Function


Code: [Select]Running 3 7zip operations


7-Zip 4.65  Copyright (c) 1999-2009 Igor Pavlov  2009-02-03

Scanning

Updating archive s:\ZipOut1.7z

Compressing  Readme.txt
Compressing  Windows Active Boot Disk.vmx
Compressing  Windows Active Boot Disk.vmxf

Everything is Ok

7-Zip 4.65  Copyright (c) 1999-2009 Igor Pavlov  2009-02-03

Scanning

Updating archive s:\ZipOut2.7z

Compressing  Readme.txt
Compressing  Windows Active Boot Disk.vmx
Compressing  Windows Active Boot Disk.vmxf

Everything is Ok

7-Zip 4.65  Copyright (c) 1999-2009 Igor Pavlov  2009-02-03

Scanning

Updating archive s:\ZipOut3.7z

Compressing  Readme.txt
Compressing  Windows Active Boot Disk.vmx
Compressing  Windows Active Boot Disk.vmxf

Everything is Ok

Completed 7z operations

Files produced:

 Volume in DRIVE S is USB-1
 Volume Serial Number is 2C51-AA7F

 Directory of s:\

24/10/2010  04:17 PM             1,561 ZipOut1.7z
24/10/2010  04:17 PM             1,561 ZipOut2.7z
24/10/2010  04:17 PM             1,561 ZipOut3.7z
               3 File(s)          4,683 bytes
               0 Dir(s)  156,771,778,560 bytes free

DoneI have tidied things up a bit; also I show how to use QUOTES around paths/filenames with SPACES. Inside strings, quotes need "escaping". That is,  to get one quote mark inside a VBScript string, you need two in the code that produces the string.

Code: [Select]wscript.echo "Running 3 7zip operations"
Run "7z a ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\7zip Archives\ZipOut1.7z"" ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\Folder with spaces\*"""
Run "7z a ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\7zip Archives\ZipOut2.7z"" ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\Folder with spaces\*"""
Run "7z a ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\7zip Archives\ZipOut3.7z"" ""S:\Test\Batch\After 16-10-2010\vbs-samewindow\Folder with spaces\*"""
wscript.echo "Done"

Function Run (ByVal cmd)
Set sh = CreateObject("WScript.Shell")
Set wsx = Sh.Exec(cmd)
Do
   Status = wsx.Status
   WScript.StdOut.Write wsx.StdOut.ReadAll()
   WScript.StdErr.Write wsx.StdErr.ReadAll()
   If Status <> 0 Then Exit Do
   WScript.Sleep 10
Loop
Run = wsx.ExitCode
End Function

296.

Solve : VBS - Replace String where not 0 or 1?

Answer»

I have a value "00000000" without quotes where I am adding a 1 to any of the positions if a value has changed in an input file but in some cases I will end up with a value of "00130012" but what I would like my end result to be is only 0(unchanged) or 1(changed) in any position ... in other works if the value is greater then 1 I want to change it back to a 1. I'm trying to figure out if the easiest way to do this would be a replace function of some SORT? I'm thinking there would have to be something simpler then a doing a split and checking each value. Or instead of the above is there a way to check the position of a digit within the value to see if ALREADY 1, if it is don't add again. I COULD do 8 counters for each position that if greater then 0 add 1 to the position but keeping track of a bunch of counters seems like a lot of work. why don't you show us your code so far? That would save one *censored* of a lot of time asking questions. Why don't you, instead of adding 1 to a position, check if the digit in that position is already changed to 1 and if it is, leave it alone?

Ended up using counters to track if I had already added a 1 to that position. Not sure how to go about checking if the position already has a 1 within a number.

Didn't post the code as it is quite messy and very much spaghetti code. Not really sure yet how to clean it up into tidy functions but at least it works and does what I want for now. I'll still posted if you CARE to see as I'm always interested in learning a cleaner meaner approach. Quote from: nothlit on October 29, 2010, 01:30:52 PM

Ended up using counters to track if I had already added a 1 to that position. Not sure how to go about checking if the position already has a 1 within a number.

I am wondering... what are you going to do when you get to more than 9 changes for any particular position? Whne the number of changes is no longer a single digit?

But assuming you never reach that state, you could

create an empty string
go through your string e.g. "00130012" character by character
for each character of your string, if it is an 0 add a 0 to your new string otherwise add a 1 to your new string.

e.g.
Code: [Select]MyString="00130012"
NuString=""
For i=1 To 8
    If Mid(MyString,i,1)="0" Then
       NuString=NuString & "0"
    Else
       NuString=NuString & "1"
    End If
Next
REM NuString now reads 00110011
But why don't you just have an array with 8 elements, set them all to 0 initially and then it's easy to check if an element is 0 and if it is, change it to 1, and if it isn't 0, leave it alone. At the end read out the elements into a string like above.





My messy code ...
Code: [Select]Option Explicit
'''''''''''''''''
'''''''''''''''''This script creates flat file for ORC research.
'''''''''''''''''
Dim objOutputFile, s, objFS, objArgs, strInputFile, objFile, strOutputfile
Dim objFSO, boolMatchCaseSensitive, objInputFile, intArgCount, s1
Dim Count, dater, Branchn, a
Dim StrDate, StrTime

Dim origBatch, origTrans, origOLD, origISN, origAUX, origRT
Dim origwAUX, origACCT, origTC, origAMT

Dim storBatch, storTrans, storOLD, storISN, storAUX, storRT
Dim storwAUX, storACCT, storTC, storAMT

Dim storAUXn, storRTn, storwAUXn, storACCTn, storTCn

Dim strOutputFilePath

Dim editFlds, stroutput

Call intialize()


Set objFS=CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8

Set objArgs = WScript.Arguments
'strInputFile = objArgs(0)
intArgCount = WSCript.Arguments.Count
'Check for at least first two arugments. First arugment is input, second is outputfile(DAT format)
if intArgCount < 2 then
MsgBox ("Need input file as first argument")
MsgBox ("Need ouput file as second argument")
WScript.Quit(99)
Else
strInputFile = objArgs(0)
'strOutputfile = "???.???"
strOutputFile = objArgs(1)
End If
'Check if Inputfile (argument1) exist, if not then exit with Error
If objFS.fileExists(strInputFile) Then
ELSE
MsgBox (strInputfile & " does not exist")
WScript.Quit(99)
End If
'MsgBox strOutputFile
'Set objFile = objFS.OpenTextFile(strInputFile)
If objFS.fileExists(strOutputfile) Then objFS.DeleteFile(StrOutputfile)
strOutputFilePath = objFS.GetParentFolderName(strOutputfile)
'If Not exists(strOutputFilePath) then
'CreateFolder(strOutputFilePath)
'End If
Set objInputFile = objFS.OpenTextFile(strInputFile, intForReading, False) 'Open Inputfile to read line by line (s variable in do loop)
Set objOutputFile = objFS.OpenTextFile(strOutputFile,intForAppending, True) 'Open Outputfile and set append mode for writing to file

Do While objInputFile.AtEndOfStream <> True
s = objInputFile.ReadLine()

If InStr (s,"Original") > 0 Then
If Count <> 0 Or editFlds <> 00000000 Then
If Count = 0 Then
objOutputFile.WriteLine origISN & " " & "01" & " " & editFlds
Else
objOutputFile.WriteLine stroutput & " " & editFlds
End If
End If
'stroutput = ""
'Count = 0
'editFlds = 00000000
Call intialize()

'origBatch = Trim(Mid(s,1,7))
'origBatch = Replace(origBatch, " ", "")
'origBatch = Replace(origBatch, " ", "")
'origTrans = Trim(Mid(s,7,8))
'origTrans = Replace(origTrans, " ", "")
'origTrans = Replace(origTrans, " ", "")
'origOLD   = Trim(Mid(s,15,9))
'origOLD = Replace(origOLD, " ", "")
'origOLD = Replace(origOLD, " ", "")
origISN   = Trim(Mid(s,25,10))
origISN = Replace(origISN, " ", "")
origISN = Replace(origISN, " ", "")
origAUX   = Trim(Mid(s,35,9))
origAUX = Replace(origAUX, " ", "")
origAUX = Replace(origAUX, " ", "")
origRT    = Trim(Mid(s,44,11))
origRT = Replace(origRT, " ", "")
origRT = Replace(origRT, " ", "")
origwAUX  = Trim(Mid(s,54,9))
origwAUX = Replace(origwAUX, " ", "")
origwAUX = Replace(origwAUX, " ", "")
origACCT  = Trim(Mid(s,63,18))
origACCT = Replace(origACCT, " ", "")
origACCT = Replace(origACCT, " ", "")
origTC    = Trim(Mid(s,81,7))
origTC = Replace(origTC, " ", "")
origTC = Replace(origTC, " ", "")
'Not using DESCRIPTION at this time
origAMT   = Trim(Mid(s,99,14))
origAMT = Replace(origAMT, " ", "")
origAMT = Replace(origAMT, " ", "")

End If

If InStr (s,"ChangedTo") > 0 Then
'storBatch = Trim(Mid(s,1,7))
'storBatch = Replace(storBatch, " ", "")
'storBatch = Replace(storBatch, " ", "")
'storTrans = Trim(Mid(s,7,8))
'storTrans = Replace(storTrans, " ", "")
'storTrans = Replace(storTrans, " ", "")
'storOLD   = Trim(Mid(s,15,10))
'storOLD = Replace(storOLD, " ", "")
'storOLD = Replace(storOLD, " ", "")
storISN   = Trim(Mid(s,25,11))
storISN = Replace(storISN, " ", "")
storISN = Replace(storISN, " ", "")
storAUX   = Trim(Mid(s,36,10))
storAUX = Replace(storAUX, " ", "")
storAUX = Replace(storAUX, " ", "")
storRT    = Trim(Mid(s,45,10))
storRT = Replace(storRT, " ", "")
storRT = Replace(storRT, " ", "")
storwAUX  = Trim(Mid(s,55,9))
storwAUX = Replace(storwAUX, " ", "")
storwAUX = Replace(storwAUX, " ", "")
storACCT  = Trim(Mid(s,63,19))
storACCT = Replace(storACCT, " ", "")
storACCT = Replace(storACCT, " ", "")
storTC    = Trim(Mid(s,81,7))
storTC = Replace(storTC, " ", "")
storTC = Replace(storTC, " ", "")
'Not using DESCRIPTION at this time
storAMT   = Trim(Mid(s,100,14))
storAMT = Replace(storAMT, " ", "")
storAMT = Replace(storAMT, " ", "")
'MsgBox "origAMT:"& origAMT &"storAMT:"& storAMT
If Count = 0  Then
If origAMT = 0.00 And storAMT > origAMT Then
'objOutputFile.WriteLine origISN & " " & "00"
stroutput = origISN & " " & "00"
Count = Count + 1
ElseIf origAMT <> storAMT Then
'objOutputFile.WriteLine origISN & " " & "02"
stroutput = origISN & " " & "02"
Count = Count + 1
End If
End If

If origAUX <> storAUX And storAUXn = 0 Then
editFlds = editFlds + 01000000
storAUXn = storAUXn + 1
End If
'If origRIC <> storRIC Then
'editFlds = editFlds + 00100000
'End If
If origRT <> storRT And storRTn = 0 Then
editFlds = editFlds + 00010000
storRTn = storRTn + 1
End If
If origwAUX <> storwAUX And storwAUXn = 0 Then
editFlds = editFlds + 00001000
storwAUXn = storwAUXn + 1
End If
If origACCT <> storACCT And storACCTn = 0 Then
editFlds = editFlds + 00000100
storACCTn = storACCTn + 1
End If
If origTC <> storTC And storTCn = 0 Then
editFlds = editFlds + 00000010
storTCn = storTCn + 1
End If
If origAMT <> storAMT Then
If Count = 1 Then
editFlds = editFlds + 00000001
Count = Count + 1
End If
End If
editFlds = Right("00000000" & editFlds, 8)

End If
Loop
objOutputFile.Close
        Set objOutputFile = Nothing
        Set objFS = Nothing
'WScript.Echo "Completed"
WScript.Quit()

Function intialize()

editFlds = 00000000
' ^Empty SERIAL RIC(Pos44) TR FLD4 AMT TC AMT
Count = 0

storAUXn = 0
storRTn = 0
storwAUXn = 0
storACCTn = 0
storTCn = 0

End Function

An array isn't a bad idea, considered it but as you can see above still very messy.
297.

Solve : Vista copy command failure?

Answer»

Vista Home edition:
I WROTE a simple batch file as follows to copy a group of dll & ocx files from a USB drive to my hard drive, and then register them individually.

Code: [Select]copy "\MiscDLLs\*.*" "C:\MyProgram\"

regsvr32.exe "C:\MyProgram\ccrpFD.ocx"
regsvr32.exe "C:\MyProgram\comct232.ocx"
regsvr32.exe "C:\MyProgram\msvbvm50.dll"
regsvr32.exe "C:\MyProgram\richtx32.ocx"

When I run the batch file with the routine double-click, the copy command is successful, but ... the four regsvr32.exe commands fail.
So ... I tried Right-click - "Run as Administrator". This time the four files were each registered successfully. (Note that the four files had already been copied to the destination folder.)

But, here's the weird part, I WANTED to test the batch file again from the beginning so I deleted the four files from MyProgram and tested the batch file again. It failed!

After repeated testing, I discovered that when the batch file was "Run as Administrator" the copy command failed and then the four regsvr32.exe commands would also fail because the four files were not available to be registered. Yet, when run as normal with the double-click the copy command worked every time. (but ... the four regsvr32.exe commands fail.)

So here's the question: "Why does the copy command fail when "Run as Administrator" is used?
I assume that there must be a syntax error involed, but OK, I may have partially figured out the answer.

In the copy cmd: Code: [Select]copy "\MiscDLLs\*.*" "C:\MyProgram\"I intentionally left out the drive letter of the USB drive because the drive letter will vary from one machine to another. Normally, "DOS"(or Windows CMD) looks on the current drive and fills in the current drive letter completing the path for me. (This works every time when the batch is run normally.)

The error that I am receiving is: Quote

The SYSTEM cannot find the path specified.
That indicates to me that when the batch is "Run as Administrator" it somehow LOSES it's ability to see the current drive (the USB drive), it then is unable to find the path.

Is there any way to avoid this when running a batch file "as Administrator"?
Or is there a way to use an environment variable that would specify the correct drive letter of the USB drive for me?I think "Run as administrator" changes the current directory. If you put the line...

echo %cd%

... at the start of your batch you will see what it reports when run as ordinary user and as administrator.

However there is a way around this - every batch file knows its own drive letter, path and name and some more stuff besides.

The variable %0 holds the information and you can use the standard  d,n,p,x, etc variable modifiers to extract it. You put a tilde (~) and a letter after the percent sign. For example %~d0 holds the drive letter and colon. You can use upper or lower case letters but the convention is to use lower case.

So you could put

Code: [Select]copy "%~d0\MiscDLLs\*.*" "C:\MyProgram\"
Note that the directory, path, etc obtained this way refer to the actual drive that the batch is stored on and do not change, and are independent from the current directory that the batch is being run from, so I expect that this will be suitable for your purposes.

This is IDme.bat. It is on a pendrive which has the letter G, in the root directory...

Code: [Select]echo off
echo Drive letter         %~d0
echo Folder               %~p0
echo Name                 %~n0
echo Extension            %~x0
echo Drive\path\name      %~dpnx0
echo fully qualified path %~f0
echo File date            %~t0         
echo File size in bytes   %~z0
pause

I double click on it in Explorer and I see this in the command window that opens...


Code: [Select]Drive letter         G:
Folder               \
Name                 IDme
Extension            .bat
Drive\path\name      G:\IDme.bat
fully qualified path G:\IDme.bat
File date            18/10/2010 06:25 PM
File size in bytes   291
Press any key to continue . . .

The variable modifiers also work on parameters %1 to %9 passed from the command line, as well as the FOR variables %%a - %%z and %%A - %%Z, and you can see a list in the FOR documentation obtained by tyoing FOR /? at the prompt. The date is shown according to your local settings.





 I'm sure that will work. It's exactly what I was looking for!

Thanks!

This is definately a keeper. I've already thought of a few other applications for the information you provided. Thanks again!
298.

Solve : download xls from a webpage with a batch file?

Answer»

Hi,

I want to download a xls that is LOCATED on a webpage.
I USE  rundll32 to OPEN a SHORTCUT referring to the xls and I'm arriving on the "file download" screen that asks me if i want to open or save the file.

Is is possible the i can save the file to specific location WITHOUT the screen?

Kind Regards

Koen

299.

Solve : Create a folder prior to moving files??

Answer»

I GOT the following code:

Code: [Select]for /f "tokens=*" %%c in ('dir "C:\Source FOLDER" /a:-d /s /B') do MOVE /y "%%c" "C:\Destination folder"

rd /s /q "C:\Source folder"

It empties all files from the Source folder as well as its sub folders.
It then deletes the Source folder and its remaining subs.

How can I tell it to create the destination folder if it doesn't already exist prior to moving the files? Code: [Select]if not exist "C:\Destination folder" md "C:\Destination folder"Right, but where in that first line would I put it?You would put it before the first line, which will now be the second line.
Right...
Stupid me...


I was THINKING it needed to be in the middle somewhere since the code had already grabbed the files out of their folders...If you want to move a file from folder A to folder B, it is necessary to first ensure that folder B exists. Before you even start.Yeah, brain fart on my part I suppose...

In my defense, I copy/pasted the code from elsewhere...

300.

Solve : dhcp devices?

Answer»

Hi CH,

Im not sure if people will be able to help on my query.

CURRENTLY, we have a particular scope that is constantly getting full... we have also amended the lease time to try and refresh it quicker than others...

Im just wondering... because most of these devices are infact offline and taking valuable leases is there any command I can run to tell me the offline ones?

Currently, what im doing is exporting the devices to a .txt file and then replacing with the built in 'Replace' feature in notepad to create: PING ADDRESS HERE -N 1

The above would then process all the devices so I can paste it into CMD and then one by one tell me which one responds or which ones dont of which I then delete...

Its just a query... but would be great if theres a quicker way.

Thank you.Hi,

Can't you use a program like netscan? this SCAN's all the ip aresses in a range.

Kind regards

KoenIt's not clear what you are trying to do.  Are you an ISP?  Why are you concerned about leases?  What kind of devices are you dealing with?