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.

351.

Solve : Issue with multiple sorts in one dir instance.?

Answer»

Hi All,

I'm not too good on the finer skills of dos, but I did create the following batch file from code scraps:

echo off
setlocal
set srcDir=\\goldals\interfaces$\ZADC\set destdir=\\mbfgoldals\dcsinterfaces$\ZADC\Pickup
set testdir=\\goldals\interfaces$\ZADC\DTS_Pickup\test
set lastmod=
pushd "%srcDir%"
for /f "tokens=*" %%a in ('dir M_??_*.txt /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&GOTO :eof
copy "%lastmod%" "%destDir%"
set lastmod1=
pushd "%srcDir%"
for /f "tokens=*" %%b in ('dir M_A*.txt /b /od 2^>NUL') do set lastmod1=%%b
if "%lastmod1%"=="" echo Could not locate files.&goto :eof
copy "%lastmod1%" "%destDir%"
pushd "%destDir%"
copy /a M*.txt Sales.txt
move M*.txt "%testDir%"


What it does is take the 2 newest dated files (of 2 different types), and concatenates it into a new file.

The issue I have is that there are now multiple files of a type on a certain date, and as such I need to
get the LARGEST SIZED newest dated file.

Thus in this line 
dir M_A*.txt /b /od 2^>NUL
I've tried the sort switches /o:ds, but it only  sorts one instance at a time.

I'm using XP version 5.1.2600 command line.

Is there a way to sort twice in one instance using dir?

Or what is my best solution?

Thanks! :-)
Quote

Is there a way to sort twice in one instance using dir?

No * That is the short answer. DOS is not a full feature database manager.
Yes, if you can explain what you want to do. In plain English.

Do you mean to create a list of ITEMS sorted on two fields?

In COMPUTER program a collection of code fragments is of little value if you do not have an understanding of what they mean. Nd books have been written about how important it is to clearly express thoughts so others may help you.

Please try again. No code, just what you want do.My apologies.

I have a directory with 2 types of text file, those whose names start with M, and those starting with M_A.

On a DAILY basis, I need one of each of these two files concatenated into one new file calles Sales.txt

The criteria to determine the 2 files to use:

1) For each type, on the latest modified date (time not considered.)

2) There will be multiple files on the newest modified date, and so, in addition and for each type, it must be the largest file.

Thus, those in bold needs to be chosen from below example.

Name---Size---Modified
~~~~~~~~~~~~~~~

M1.txt---50---31/10/2010
M2.txt---60---30/10/2010
M3.txt---100 ---29/10/2010
M4.txt---23---30/10/2010
M5.txt--- 77---31/10/2010
M_A1.txt ---45---31/10/2010
M_A2.txt --- 65---30/10/2010
M_A3.txt---89---31/10/2010
M-A4.txt---42---30/10/2010
M_A5.txt---74---31/10/2010

I need to run this procedure from a batch file.
Please help me out with code.That is excellent!
Now we understand the challenge. The only suggestion I would have in your description is to do not use the expression "type" as this may cause confusion. Instead, you have a naming convention for your files. So let's substitute the word "style" in place of the word "type" to make it clear not talking about an actual file type but a naming convention you have chosen .
Reader you mentioned the use of the instance. In some context instance would have a different meaning, so let's drop the use of instance in this case.
So as I understand it, you are looking for two files that conform to your style of naming convention. Both files must be the largest of their style and of the most recent date.
I am not very good at doing one-liners. I would probably break it up into several lines of code and have two FOR loops . One to identify files of the most recent dates for the two forms of your style. Then another loop to determine the largest files for the two forms of your style. At the end of that there should be only two files left that conform to your style. Then the last step would be to simply merge those two files together into your sales report. A personal preference for the sort of thing is to create a list of files and then go through the list and pick out the ones that conform to the criteria and write it to a new list. Then processing the list again and eventually end up with a list that has just the two files in it. It would not be concerned about speed, the text files would be rather small compared to the size of files. Moving files around would get to be much more intensive task. Simply creating a list of all names has very low overhead to the system.

Pardon me for not writing the code for you, I am very limited to what I'm able to do because of my personal handicap. At any time somebody like Salmon and Trout
we'll pop in here and give you a half page of code that works right the first time.

Quote from: Geek-9pm on November 19, 2010, 10:55:28 AM
Salmon and Trout

we are very flattered by your confidence (both of us).
Part of the problem is the example you posted is a mess, with nothing aligned. That can be remedied but then the problem with the sort utility rears it's ugly head. The sort utility supplied with Windows does not allow multiple fields as sort keys (unless contiguous) and you cannot mix sort order (ascending and descending) in the same pass.

VBScript does not have a native sort function. You can however use a disconnected recordset (meaning there is no underlying database) which does have sort capability.

This data was used for testing:

Quote
M1.txt---50---31/10/2010
M2.txt---60---30/10/2010
M3.txt---100 ---29/10/2010
M4.txt---23---30/10/2010
M5.txt--- 77---31/10/2010
M_A1.txt ---45---31/10/2010
M_A2.txt --- 65---30/10/2010
M_A3.txt---89---31/10/2010
M-A4.txt---42---30/10/2010
M_A5.txt---74---31/10/2010


Code: [Select]'On Error Resume Next

Const ForReading = 1
Const MaxCharacters = 255
Const adDouble = 5
Const adDate = 7
Const adVarChar = 200

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

rs.Fields.Append "FileType", adVarChar, MaxCharacters
rs.Fields.Append "FileName", adVarChar, MaxCharacters
rs.Fields.Append "FileDate", adDate, MaxCharacters
rs.Fields.Append "FileSize", adDouble, MaxCharacters
rs.Open

Set f = fso.OpenTextFile("C:\Temp\SplitSortCombine.txt", ForReading) 'Change as required

Do Until f.AtEndOfStream
strline = f.ReadLine
With objRE
.pattern = "---"
    strLine = .Replace(strLine, ",")
   
    .Pattern= " "
    strLine = .Replace(strLine, "")
  End With
  strFields = Split(strLine, ",")   
 
rs.AddNew
If Mid(strFields(0), 1, 2) = "M_" Then
rs("FileType") = "A"
Else
rs("FileType") = "B"
End If

rs("FileName") = strFields(0)
rs("FileSize") = CDbl(strFields(1))
rs("FileDate") = strFields(2)
rs.Update
Loop

rs.Sort = "FileType ASC, FileDate DESC, FileSize DESC"
rs.MoveFirst
fileOne = rs.Fields.Item("FileName")

rs.Sort = "FileType DESC, FileDate DESC, FileSize DESC"
rs.MoveFirst
fileTwo = rs.Fields.Item("FileName")

WScript.Echo FileOne, FileTwo

rs.Close
f.Close

Save the script with a vbs extension.

Code: [Select]echo off
::
:: Change the path and label of c:\temp\SplitSortCombine.vbs as required
:: Change the path and label of output.dat as required
::
for /f "tokens=1-2" %%i in ('cscript //nologo c:\temp\SplitSortCombine.vbs') do (
  echo copy %%i+%%j output.dat


Save the script with a bat extension. The batch file will run the vbs script. The vbs script reads the data posted above. The results are on the console showing what the copy command will look like. When you're ready, remove the word echo from this line: echo copy %%i+%%j output.dat. You can change the order of the files by reversing %%i and %%j.

Good luck.
Once the VBScript solution was done, I realized with a little smoke and mirrors this could actually be done with only batch code:

Code: [Select]echo off
setlocal enabledelayedexpansion

for /f "tokens=1-5 delims=-/ " %%i in (c:\temp\splitsortcombine.txt) do (
  set fname=%%i
  set fsize=%%j
  set fdateDD=%%k
  set fdateMM=%%l
  set fdateYY=%%m

  if !fsize! LSS 10 (set fsize=00000!fsize!
    ) else if !fsize! LSS 100 (set fsize=0000!fsize!
    ) else if !fsize! LSS 1000 (set fsize=000!fsize!
    ) else if !fsize! LSS 10000 (set fsize=00!fsize!
    ) else if !fsize! LSS 100000 (set fsize=0!fsize!
  )   
   
  if "!fname:~0,2!" EQU "M_" (echo !fdateYY!!fdateMM!!fdateDD!,!fsize!,!fname! >> A.dat
    ) else (echo !fdateYY!!fdateMM!!fdateDD!,!fsize!,!fname! >> B.dat
  )   
)
 
for /f "tokens=3 delims=," %%i in ('sort A.dat') do (
  set FileOne=%%i
)

:next   
  for /f "tokens=3 delims=," %%i in ('sort B.dat') do (
    set FileTwo=%%i
  )

:next
  del A.dat
  del B.dat
  echo copy %FileOne%+%FileTwo% output.dat

As in the previous post, the results are on the console showing what the copy command will look like. When you're ready, remove the word echo from the last line in the file.

IMO the VBScript is more elegant and easier to read, but hey! that's just me.

Good luck.
352.

Solve : Save custom password??

Answer»

Is there a way to let the batch file SAVE your password? For example with this code someone could easily see the password:
Code: [Select]echo off
color 0a
:start
echo Whats the password?

set /p pass=
if %pass%==12345 (
goto :right
)

cls
goto :start

:right
cls
echo You got it right.
pause >nul

So is there a way to save your password into another file and then call that file to see if the passwords match? For example, it would ask you for your password,
then somehow save that password into a .txt (not that secure i know will change) and move it to a 'secret' place (my 'Documents' folder in this example)

So my theory is:

Code: [Select]echo off
if exist C:\Users\UserAccount\Documents "secret.txt" goto :alreadyexist
cls
echo Set a password
echo.
set /p yourpass=
echo %yourpass% >>secret.txt
move secret.txt "C:\Users\UserAccount\Documents"
exit

:alreadyexist
cls
echo Type in your password you saved:
echo.
set /p savedpass=
if %savedpass%==%secret.txt% goto :right
goto :alreadyexist

:right
cls
echo The password in the .txt file matches the one you typed in.
pause >nul
exit


The main part i can't figure out is this:

Code: [Select]set /p savedpass=
if %savedpass%==%secret.txt% goto :right

Sorry if this is confusing but someone please help. 
I've always believed that the creativeness that goes into a batch file is INVERSELY proportional to it's readability. This little snippet throws all the rules of KISS out the window, and barrels forward into the Looking Glass.

Code: [Select]echo off
setlocal
echo hP1X500P[PZBBBfh#b##[email protected]`$fPf]f3/f1/5++u5>hide.com

:retry
  set /p userId=Enter UserId:
 
  set /p password=Enter Password: <nul
  for /f "tokens=*" %%i in ('hide.com') do set password=%%i
  if exist %username%.txt (goto file) else (goto nofile)
 
:file
  for /f "tokens=* delims=" %%i in (%username%.txt) do set %%i
  if %userid%==%id% if %password%==%pswd% echo. & echo You Are Logged In & goto cleanup
  cls
  echo UserId or Password Invalid...Try Again
  goto retry
 
:nofile
  (
  echo id=%UserId%
  echo pswd=%password%%
  ) >> %username%.txt
  echo. & echo Password File Saved...%date% %time%
 
:cleanup
  del hide.com 

The password file is labeled with your username and a txt extension. The file is only created if it does not exist. Subsequent runs use the file to compare the userid and password.

The userid and password are case sensitive.

The hide.com file is used to keep the password hidden on the console. The password is stored as plain text and is not ENCRYPTED or encoded.

I suggest you make any changes necessary concerning file paths or names.

Good luck.
Thanks a lot! Could you please get rid of the 'hide.com' thing (i know it hides the pass) because whatever i do it seems that i can't delete that part without making the script stop 

Another main part i hope you can change (because I unfortunately can't  ) is how could i move the file to a 'secret' place so no one would just open it up? Because I tried adding that and It couldn't find my file :/ Please make the example save and open the .txt file into this 'example' directory: C:\Users\%username%\Documents

Modifications have been made. The password file is now labeled secret.txt and lives in C:\Users\%username%\Documents. I changed the password file path to a variable so changes can be made to a single line. Also the hide password feature has been removed.

Code: [Select]echo off
setlocal
set passfile=c:\users\%username%\documents

:retry
  set /p userId=Enter UserId:
  set /p password=Enter Password:
  if exist %passfile%\secret.txt (goto file) else (goto nofile)
 
:file
  for /f "tokens=* delims=" %%i in (%passfile%\secret.txt) do set %%i
  if %userid%==%id% if %password%==%pswd% echo. & echo You Are Logged In & goto :eof
  cls
  echo UserId or Password Invalid...Try Again
  goto retry
 
:nofile
  (
  echo id=%UserId%
  echo pswd=%password%%
  ) >> %passfile%\secret.txt
  echo. & echo Password File Saved...%date% %time%


 


Omg    Thank you so much!! Finally i got my answer...this was EXACTLY what i NEEDED. Thanks A LOT!

353.

Solve : substring usage?

Answer»

Hi!

I couldn't find anything posted before, but I'll apologize upfront now if this is a repeat.

I'm trying to find the syntax for extracting specific characters from a string variable within a batch file. For example, I have a variable SET to "123456789" and I wish to use the second and fifth characters in order to create a new variable "52".

tia,
Mitch
The syntax for extracting a substring is

%variablename:~A,B%

: is a colon
~ is a tilde
, is a comma

A and B are numbers or variables.

A is the offset, from the start of the main string, of the first character to EXTRACT. (0 means the first character, 1 means the second character and so on)

B is the number of characters to extract

Code: [Select]set string=hello
echo %string:~0,2%
he



your operation might proceed like this

set string=123456789
set newstring=%string:~1,1%%string:~4,1%

result 25

set newstring=%string:~4,1%%string:~1,1%

result 52

Your question is contradictory because you SAY you want to use the "second and fifth" characters but your example "52" contains the fifth character and then the second character in that order.

Of course within parentheses then delayed expansion and ! are necessary.



Salmon Trout - Thanks so much for the reply and edification.

I didn't mean to be contradictory in my example. I did it that way on purpose so as not to imply order in the usage of the substrings.

Thanks again,
MitchFurther notes...

Using this format again, where the substring is %fullstring:~A,B% and A is the offset and B is the number of characters:

A is obligatory, a positive number means count the offset from the start, a negative number means count backwards from the end.

B is optional and if it is omitted, all characters are taken up to the end of the first string.

If B is negative, then the last B characters of the string are omitted

Thus:

If string=123456789

%string:~2% is 3456789

%string:~-2% is 89

%string:~-4% is 6789

%string:~-4,2% is 67

%string:~0,-2% is 1234567

details are in the SET help, visible if you type SET /? at the prompt

Extract:

Code: [Select]    %PATH:~10,5%

would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result.  If the length is not specified, then it DEFAULTS to the
remainder of the variable value.  If either number (offset or length) is
negative, then the number used is the length of the environment variable
value added to the offset or length specified.

    %PATH:~-10%

would extract the last 10 characters of the PATH variable.

    %PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.








354.

Solve : Batch command for Pings?

Answer»

Morning all,

Im hoping someone here may be able to help me out here.
I'm  DBA and IT support Tech and have a few servers I investigate from time to time and sadly I'm NEW to my enviroment and the referance data for System names and IP addresses is rather lacking.

SO what i want to do is have a look at a few systems and return are they up, and what are the IP addresses.

So to that end i developped a really simple DOS Batch for the one but cant get the 2nd part now, just cant seem to figure it out.

Heres the Batch file coding.

Code: [Select]:====8<-----[ Pinger V2.bat ]-----
ECHO OFF
TITLE Network Check
setlocal enabledelayedexpansion

REM -----------------------------------
REM -- Files
REM -----------------------------------

SET MachineList=ping.txt
SET ResultsFile=results.txt

REM -----------------------------------
REM -- Checks
REM -----------------------------------

CLS
ECHO.
IF NOT EXIST "%MachineList%" (
  ECHO Cannot locate Machine List: %MachineList%
    PAUSE>NUL
      GOTO :EOF
      )
 
REM -----------------------------------
REM -- Running Notice
REM -----------------------------------

      ECHO PROCESSING all machine names in %MachineList% . . .
      ECHO.
 
REM -----------------------------------
REM -- Machine Responds
REM -----------------------------------

      FOR /f "tokens=*" %%M in (%MachineList%) do CALL :CHECK "%%M"
          GOTO :EOF

      :CHECK
      SET Machine=%~1
      SET Machine=%Machine: =%

      PING -w 1000 %Machine%>NUL
        IF %ERRORLEVEL% NEQ 0 ECHO %Machine% did not respond at %Time%>>%ResultsFile%
        IF NOT %ERRORLEVEL% NEQ 0 ECHO %Machine% responded at %Time%>>%ResultsFile%

      EXIT /B

 
 
:EOF
:====8<-----[ Pinger V2.Bat]-----

Can someone possibly help me in adding a IP value to my "IF %ERRORLEVEL% NEQ 0 ECHO %Machine% did not respond at %Time%>>%ResultsFile%" string

Thanks a TON in advance.I also monitor my servers etc and use a cheap and great piece of software called Alert PING Pro. You add your systems to monitor to it and you can create your own programs to execute if you LIKE or be notified by e-mail etc if there are problems. I wrote a C++ program that worked between a modified VOIP phone, the software, and a handset release relay connected through serial port that would TRIGGER handset release to activate phone, so that it would call my cell phone repeatedly and play out a *.wav file instructing the error condition. This way I got called as the problem was detected and on my drive to the workplace I had a hint as to where the problem was etc. It also has many other features such as color coding ping response times etc, so if you want to watch areas of your network for bottlenecking etc.

http://www.softpedia.com/get/Network-Tools/Network-Monitoring/AlertPingPro.shtml

355.

Solve : Searching entry within a file?

Answer»

Hi All,

I am trying to write a bat file that should check for a particular entry within a file. On finding, it should proceed to the next step or terminate right there.

I have managed to put in the FOLLOWING piece of code but it's not helping me with what I want to do:

Code: [Select]ECHO OFF
REM========================================

SET LOG=\tmp\check.log

REM ====================================================
REM 1) Check for entry "A"
REM ====================================================
E:
cd \ABC

IF EXIST temp.log.(FINDSTR "A" temp.log.)ELSE echo temp.log. missing >>%LOG%
IF %ERRORLEVEL% NEQ 0 (
ECHO Failed to find entry A in temp.log >>%LOG%
goto EXITERROR ) ELSE (
goto step2
)

REM ====================================================
REM 2) Check for entry "B"
REM ====================================================
:step2
E:
cd \ABC

IF EXIST temp.log.(FINDSTR "B" temp.log.)ELSE echo temp.log. missing >>%LOG%
IF %ERRORLEVEL% NEQ 0 (
ECHO Failed to find entry B in temp.log >>%LOG%
goto EXITERROR ) ELSE (
goto step3
)

REM ====================================================
REM 3) Check for entry "C"
REM ====================================================
:step3
E:
cd \ABC

IF EXIST temp.log.(FINDSTR "C" temp.log.)ELSE echo temp.log. missing >>%LOG%
IF %ERRORLEVEL% NEQ 0 (
ECHO Failed to find entry C in temp.log >>%LOG%
goto EXITERROR ) ELSE (
ECHO All entries found in the file>>%LOG%
)

REM ==========================
REM ERROR Code
REM ==========================
:EXITERROR
The file temp.log resides under the folder ABC under E: drive. I want to check for the entry "A" within this file before proceeding with the next step. The script should simply go to the next step if it finds, otherwise it should exit by alerting the user.

Please can you help?

Many thanksWas able to salvage "check for entry "A". The other letters should follow the same pattern.

Code: [Select]echo off
rem========================================

set log=\tmp\check.log

rem ====================================================
rem 1) check for entry "a"
rem ====================================================
e:
cd \abc

if exist temp.log (findstr "a" temp.log) else (echo temp.log. missing >>%log%)
if %errorlevel% neq 0 (
  echo failed to find entry a in temp.log >>%log%
  goto exiterror ) else ( goto step2
)

 c:\test>type  swados.bat
echo off
echo. > c:\tmp\check.log
set log=c:\tmp\check.log


cd c:\test\abc

if exist temp.log (findstr "a" temp.log) else (echo temp.log. missing >>%log%)
echo errorlevel=%errorlevel%
if %errorlevel% neq 0 (
  echo failed to find entry a in temp.log >>%log%
  goto exiterror ) else ( goto step2)

)
:exiterror
echo errorlevel=%errorlevel%
exit /b
:step2
cd c:\test\abc
findstr b temp.log

if EXIST temp.log.(FINDSTR "b" temp.log.)ELSE (echo temp.log. missing >>%log%)
echo errorlevel=%errorlevel%
if %errorlevel% NEQ 0 (
echo Failed to find entry B in temp.log >>%log%
goto exiterror ) else (
goto step3 )

:step3
cd c:\test\abc
findstr  c  temp.log

if EXIST temp.log.(findstr "c" temp.log.)else (echo temp.log. missing >>%log%)
if %errorlevel% NEQ 0 (
echo Failed to find entry C in temp.log >>%log%
goto exiterror ) else (
echo All entries found in the file>>%log%)

cd c:\tmp\
echo type  check.log
type check.log

Output:

c:\test> swados.bat
a
errorlevel=0
b
errorlevel=0
c
type  check.log

All entries found in the file

c:\tmp>

_______________________________________ ________


C:\test>cd  abc

C:\test\abc>dir
 C:\test\abc>type  temp.log
a
b
x


C:\test>type  sw2dos.bat
echo off
echo. > c:\tmp\check.log
set log=c:\tmp\check.log


cd c:\test\abc

if exist temp.log (findstr "a" temp.log) else (echo temp.log. missing >>%log%)
echo errorlevel=%errorlevel%
if %errorlevel% neq 0 (
  echo failed to find entry a in temp.log >>%log%
  goto exiterror ) else ( goto step2)

)
:exiterror
echo errorlevel=%errorlevel%
cd c:\tmp\
echo type  check.log
type check.log
pause
exit /b
:step2
cd c:\test\abc
findstr b temp.log

if EXIST temp.log.(FINDSTR "b" temp.log.)ELSE (echo temp.log. missing >>%log%)
echo errorlevel=%errorlevel%
if %errorlevel% NEQ 0 (
echo Failed to find entry B in temp.log >>%log%
goto exiterror ) else (
goto step3 )

:step3
cd c:\test\abc
findstr  c  temp.log

if EXIST temp.log.(findstr "c" temp.log.)else (echo temp.log. missing >>%log%)

if %errorlevel% NEQ 0 (
echo Failed to find entry C in temp.log >>%log%
goto exiterror ) else (
echo All entries found in the file>>%log%)

cd c:\tmp\
echo type  check.log
type check.log

Output:

C:\test>sw2dos.bat
a
errorlevel=0
b
errorlevel=0
errorlevel=1
type  check.log

Failed to find entry C in temp.log
Press any key to continue . . .

c:\tmp> Quote from: donald99 on December 17, 2010, 06:43:58 PM

c:\test>type  swados.bat

[etc]


Hi, Bill! No change in the posting style, I see.
Oh man, you spoiled it! Donald (aka Bill) has been BIRD dogging a few of my posts lately and offering up snippet explanations with his usual inimitable style. This certainly has added value to my usual battleship gray code boxes and has turned CH into a destination website.

Can't catch a break anywhere. Yes,  reply 2 added INSIGHT and output to the thread.
Now most readers can UNDERSTAND the question by Swados
and the solution offered by SidewinderHere we go again... 

Hello
356.

Solve : Minimizing to task bar?

Answer»

Is there a way a batch file can minimize any program to the task bar? Like keep it running in the background but not like keeping a bookmark. This will be extremely helpful because i hate over crowded windows O.o

Please and thank you

P.S. I have no clue how do this and can't find anything on the internet so i don't think it possible but it's worth a TRY

If you don't know what i'm talking about, refer to the picture...

Quote from: shanked on November 26, 2010, 11:38:12 PM

Is there a way a batch file can minimize any program to the task bar?

I doubt it. Batch language is a command language not a programming language. If it could do everything people seem to think it can do it would be truly amazing.

There are tools on most Windows machines that can do this. If you want to try VBScript, I probably have something in the snippet closet.

Let us know.  Quote from: shanked on November 26, 2010, 11:38:12 PM
Is there a way a batch file can minimize any program to the task bar? Like keep it running in the background but not like keeping a bookmark. This will be extremely helpful because i hate over crowded windows O.o

Here's the thing. there is no such term or component of the Windows taskbar that contains a "bookmark". those are called task buttons (or something to that effect). Not bookmarks.

A button appears on the taskbar for every top-level window that has the appropriate style set; the Notification Area is a completely separate location; programs do not minimize to the notification area. Those programs which claim to are not minimizing at all; they are merely making their window invisible and displaying a new icon in the notification area.

Now, the problem with any "batch" solution is that the Shell_NotifyIcon() Function (the one responsible for adding new ICONS to the notification area) takes as a parameter a window handle; you could pass any valid handle in, but the function will SEND messages to that window when you mess with the notification icon; so really, what you would need to do in any such solution is:

-Create a dummy window, or otherwise manage to get a window handle whose Window Procedure you can get a hold of (or that handles the appropriate messages)

-Create the icon in the notification area; hide the displayed program window.

-wait for messages to be received in the dummy window. react appropriately to "restore" the previously made invisible windows.


I BELIEVE there are a number of off-the-shelf programs that can be used to "iconize" (as in, place in the system notification area) applications. Quote from: Sidewinder on November 27, 2010, 06:48:54 AM
I doubt it. Batch language is a command language not a programming language. If it could do everything people seem to think it can do it would be truly amazing.

There are tools on most Windows machines that can do this. If you want to try VBScript, I probably have something in the snippet closet.

Let us know. 

Sure Could someone please tell me how to do this via VBscript? Thanks (Kinda off-section  )I may have mis-read your post. VBScript can minimize a window to the task bar but the system tray/notification area is more problematic.

BC mentioned that there are 3rd party programs you can try  here.

Good luck. 



357.

Solve : Deleting Specific website/program?

Answer»

In one of my batch scripts i want to close a specific page of a website. The problem is when i use 'taskkill' it closes all of the pages.

For example, if i'm using Google Chrome and am on google.com and also have another google webpage open on yahoo, how do you close the yahoo page only?
I know how to do Code: [Select]taskkill /f /im chrome.exe but is there someway to do like (my theory) Code: [Select]taskkill /f /im chrome.exe www.yahoo.com

Also, if there is a way to do that ^ Is it possible to close a specific TAB? Like the same scenario, one page is on Google and other TAB is on Yahoo. Is there a way to close the yahoo TAB only? (Also on Google Chrome)

Please and thank you I don't think it's possible to modify PART of an application using the command promt or batch files. I could be wrong, but I doubt it's possible Quote from: polle123 on November 24, 2010, 01:13:38 PM

I don't think it's possible to modify PART of an application using the command promt or batch files. I could be wrong, but I doubt it's possible

Yeah i don't think so either, I've been looking everywhere and can't find anything :/The utility is called "killtask". It kills a task. In order to create a PROGRAM that could do something unique like that, The program would have to implement it in some way; such as Via a COM accessible object (Word, Excel, etc allow this) or via a command line argument (which is then passed to the existing instance of the program).

The reason should be rather clear; From outside a running program, all that application looks like is a process. It's possible to read and write to process memory; but without a detailed map of what is stored where and how it's laid out, that would be useless and bound to corruption.




Sometimes the BEST answer to a question is another question.

Why? Quote from: Geek-9pm on November 24, 2010, 11:35:50 PM
Sometimes the best answer to a question is another question.
Definitely. Let me try.

Quote
Why?

Why not?Our resident troll, Billrich/Larrylong whatever the flip he calls himself now, has sent me a ridiculous PM in this regard; clearly he knows that posting on the forum openly is simply going to get him banned again, and so it seems that after circumventing the last ban he's decided instead to merely PM people, and that this will somehow conceal him.

Anyway, this is the PM:

Quote
Kill Yahoo

C:\test>type killyahoo.bat
echo off

rem START "yahoo" "C:\Program Files\Internet Explorer\iexplore.exe" http://www.yahoo.com/

start "yahoo*"
taskkill /fi "WINDOWTITLE eq yahoo*"

Rem Ref: http://it.toolbox.com/blogs/database-solutions/kill-a-process-in-windows-bat-19875

C:\test>start "yahoo" "C:\Program Files\Internet Explorer\iexplore.exe" http://www.yahoo.com/

Output:

C:\test>killyahoo.bat
SUCCESS: Sent termination signal to the process with PID 2636.
SUCCESS: Sent termination signal to the process with PID 3772.

C:\test>

p.s.  ref:   Deleting Specific website/program
 I know how to do

taskkill /f /im chrome.exe but is there someway to do like (my theory)

taskkill /f /im chrome.exe www.yahoo.com

You'll note several interesting things that old Bill overlooks:

First, you'll note that his example is using Internet Explorer, which clearly isn't Google chrome. Second, you'll see that he is closing a task based on a window title; clearly he is working under the false assumption that the version of IE in use would be Version 6 or earlier, since after version 7 the display switched to tabs, whereby the title of the window was only for the active tab, and even in the case that the active tab was selected, the entire window would be closed anyway.

So yes, Bill's "solution" if we can call it that (personally I'd be more likely to call a bowl of noodles a platypus), would work for his specific little subcase, but not at the scope of the original request*; after all, with IE6 and earlier each window did indeed represent an entire process, so even if we were in a whimsical fairy land where google chrome was Internet Explorer 6 (and who wants to Live in that world? Only CBMatt, probably), it's not really closing part of a process as the original post requests. Therefore my previous post still stands; unless a program provides a command-line accessible interface and provides the necessary plumbing to perform a specific task (as noted, Chrome would need to accept an argument on the command line and then be able to pipe  (via DDE or OLE or some other cross-process thing) the data to the original Chrome process, which could act accordingly and close the tab; However, Since chrome doesn't provide this option (and shall I note that firefox DOES indeed have a cmd line argument that allows you to close a tab in an open browser?) It's not possible. A third-party program could of course be used to do this task; there are python scripts designed to open pages on existing chrome processes, so I imagine it's possible to use the same plumbing to close them. This is all redundant to the context of the original post, and only serves as delicious trollfood for our dear friend Billrich (and I say that with some irony) who takes delight in the various ancillary snacks he has been given as a result of his unsolicited PMS.


* This is not an uncommon trait that he exhibits; I wouldn't be surprised if somebody asked what home remedies people had for colds and he started to list off the ingredients on a ATHLETES foot medication


Quote from: BC_Programmer on November 25, 2010, 07:53:53 PM

* This is not an uncommon trait that he exhibits; I wouldn't be surprised if somebody asked what home remedies people had for colds and he started to list off the ingredients on a athletes foot medication
Hey, does that work?  I just ran out of my cold medicine, but have some stuff for my feet. Quote from: BC_Programmer on November 25, 2010, 07:53:53 PM

So yes, Bill's "solution" if we can call it that (personally I'd be more likely to call a bowl of noodles a platypus), would work for his specific little subcase, but not at the scope of the original request*; after all, with IE6 and earlier each window did indeed represent an entire process, so even if we were in a whimsical fairy land where google chrome was Internet Explorer 6 (and who wants to Live in that world? Only CBMatt, probably), it's not really closing part of a process as the original post requests. Therefore my previous post still stands; unless a program provides a command-line accessible interface and provides the necessary plumbing to perform a specific task (as noted, Chrome would need to accept an argument on the command line and then be able to pipe  (via DDE or OLE or some other cross-process thing) the data to the original Chrome process, which could act accordingly and close the tab; However, Since chrome doesn't provide this option (and shall I note that firefox DOES indeed have a cmd line argument that allows you to close a tab in an open browser?) It's not possible. A third-party program could of course be used to do this task; there are python scripts designed to open pages on existing chrome processes, so I imagine it's possible to use the same plumbing to close them. This is all redundant to the context of the original post, and only serves as delicious trollfood for our dear friend Billrich (and I say that with some irony) who takes delight in the various ancillary snacks he has been given as a result of his unsolicited PMs.


Well this post is a little bit confusing. All i want is a yes or no answer :/ ...but anyway lemme point out your forgot a closing parenthesis xP The bolded are is where it starts but never finishes O.o ( sorry off-topic)Is shanked one of Billrich's stooge IDs?
Quote from: shanked on November 25, 2010, 11:44:37 PM
Well this post is a little bit confusing. All i want is a yes or no answer :/ ...but anyway lemme point out your forgot a closing parenthesis xP The bolded are is where it starts but never finishes O.o ( sorry off-topic)

Yeah I do that sometimes. I use parentheses far too often in my text in any case.

EDIT: hmm, maybe I should become a LISP programmer?


Quote from: BC_Programmer on November 26, 2010, 12:44:09 AM
maybe I should become a LISP programmer?

Yeth. Thatth a good idea.

358.

Solve : Bat Script for Comp Info to txt file then to a Exchange 2003 Public folder?

Answer»

First off let me make it clear I consider myself a amateur when it comes to batch scripting and I am learning as I go along and this site has been very helpful in GIVING me ides and solving some problems.  Here is a script I recently wrote that gives basic computer info into a text file:

Quote

echo off

:: Defining Variables for those of you who have come behind the creator for less confusion
:: C_Date - CURRENT Date
:: C_Time - Current Time
:: Computer_Name - the host name
:: Log_File - Name of the file that is ultimately created
:: N_Location - Network Location of file
:: Department - The department the computer is in that is being reported
:: First_Name - User first name ie Han
:: Last_Name -  Users Last name ie Solo

echo.
ECHO The purpose of this test is to gather data form a University Hospitals Computer
ECHO.
pause
echo.
set /p Last_Name=Your LAST NAME please?
echo.
set /p First_Name=and your FIRST NAME in full please (No Nicknames Thanks)?
echo.
set /p Department=The Department the computer is in ie Proctology or ER or NiCU or Psychology or Morgue?
echo.


set Computer_Name=%COMPUTERNAME%
REM echo.
REM echo Your PC ID is %Computer_Name%
REM echo.
::pause

:: for /f "tokens=1-5 delims=/ " %%d in ("%date%") do RENAME "hope.txt" %%e-%%f-%%g.txt
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do set C_Date=%%g%%e%%f
REM echo.
REM echo Current Date (YYYYMMDD): %C_Date%
REM echo.
::pause

:: for /f "tokens=1-5 delims=:" %%d in ("%time%") do rename "hope.txt" %%d-%%e.txt
for /f "tokens=1-5 delims=:" %%d in ("%time%") do set C_Time=%%d%%e%%f
REM echo.
REM echo Current Time (HHMMSS.XX): %C_Time%
REM echo.
::pause
set Log_File=%C_Date%.%Computer_Name%.%C_Time%
REM echo.
REM echo The name of the text file shall be %Log_File%.txt
REM echo.
REM pause
set N_Location="%USERPROFILE%\Desktop\%Log_File%.txt"
REM echo.
REM echo %N_Location%
REM echo.
REM pause
echo.
echo Creating Text File on your desktop...
::space
echo. > %N_Location%
echo File Created on %C_Date% %C_Time% by %USERNAME% >> %N_Location%
::space
echo. >> %N_Location%
echo Individuals name submitting the report: %Last_Name%, %First_Name% >> %N_Location%
::space
echo. >> %N_Location%
echo Department they are reporting from: %Department% >> %N_Location%
::space
echo. >> %N_Location%
echo PC ID: %Computer_Name% >> %N_Location%
::space
echo. >> %N_Location%
echo System Type: %systype% >> %N_Location%
::space
echo. >> %N_Location%
psinfo >> %N_Location%
::space
echo. >> %N_Location%
IPConfig /all >> %N_Location%
::space
echo. >> %N_Location%
echo Current Running Processes at the time report was run... >> %N_Location%
Tasklist >> %N_Location%
cls
echo.
echo Thank You %First_Name% for submitting your report to the IT^&S Service Desk.
echo We have your system information and have noted you are in the %Department% department.
echo.
echo.
echo.
echo.
echo.
echo This message will self-destruct in five seconds.
echo.
ping 127.0.0.1 -n 20 -w 1000 > nul
echo.

Simply enough I think...

The question is how do I take the finally output where ever it lands in a txt file format and have it show up in a Microsoft Exchange 2003 Public Folder?

Make sense?  Understand? Questions... comments please any advice would be very helpful.

Thanks

An amended thought... does someone know how I might send this to a email address through batch scripting or does anyone know of another script/program I can call to email a notification to?

Still doing the research myself but thought I would throw all of this out here and see what sticks! 

Thanks again...I have been shown some light on this...


Quote
mailto:to?subject=subject&cc=cc_address&bcc=bcc_address&body=message_body

to_address    The (escaped) e-mail address of the recipient; allowed formats:
[email protected]
• Full%20Name&lt;[email protected]&gt;
subject    The (escaped) subject field of the message
cc_address    The (escaped) "carbon copy" e-mail address; allowed formats:
[email protected]
• Full%20Name&lt;[email protected]&gt;
bcc_address    The (escaped) "blind carbon copy" e-mail address; allowed formats:
[email protected]
• Full%20Name&lt;[email protected]&gt;
message_body    The actual message body (escaped too)

But the syntax ELUDES me a little and I am still getting error messages.

Anyone familiar with this or have a better website to view for help then this one http://www.robvanderwoude.com/email.php

ThanksOkay after further research I have found that even if I get the syntax to work that this is not what I needed.  I think I need a third party simple executable that I can reference and use in a COMMAND line.

Anyone got any ideas?

ThanksMailto is used to pre-fill a mail form. The user is still required to click the send button.

You can try this 3rd party free program: blat. It comes as a zip file with the documentation included.

Alternatives include any Windows script language that is COM aware. (VBScript, Python, etc). If you have access to Powershell, there is a Send-MailMessage cmdlet for this purpose.

Good luck. 

359.

Solve : No more than 8 letters?

Answer»

I've been trying to make a batch file and now am stuck. In it, you get an option to type something in, but it cannot be more than 8 letters long (so it will fit on the screen)

Here is my short example of my 'limited knowledge' of this but it has major drawbacks...

Code: [Select]echo off
set /p greater=8

echo Type in something, cant be more than 8 letters long...
set /p option=
if %option% GTR %greater% goto :toohigh
etc...

This would WORK smoothly if i was using numbers picking 1-8 but that's not the case 

The major drawbacks are
1. You can only enter numbers (In order for it to actually respond to the 'goto')
2. You can only enter a number 1 at a time because if you ADD more and press enter, it doesn't work.

I want it to be able to type in a word and if it is more than 8 letters goto :toohigh or whatever, and if it's less than/equal to 8 letters to continue.
Please include NOTES on how you did this (or at least try ) so i can manipulate this later and use it for something else. Thank you I found this in the snippet closet.

Quote

I want it to be able to type in a word and if it is more than 8 letters goto :toohigh or whatever, and if it's less than/equal to 8 letters to continue.

Code: [Select]echo off
setlocal
set /p var=Enter String:

:loop
 if defined var (set var=%var:~1%& set /a length += 1 & goto loop)
 if %length% GTR 8 (goto toohigh)
 
echo fell into this (continue)
goto :eof

:toohigh
  echo got here from a goto

Quote
Please include notes on how you did this (or at least try ) so i can manipulate this later and use it for something else. Thank you

Explanations are extra.  Please pay the cashier on your way out.

Basically all the work is done in the if defined line. Each repetition of the loop strips off a single character from the string and adds 1 to the length counter. When no characters exist in the string, the loop ends and the logic flows to either the :toohigh label or simply continues. As with all batch files, if you turn on echo, you can see exactly how it runs.

Good luck.  Wow thanks A LOT this really helped Will put in my 'batch notes' Awww..i NEED more help now :/

So far my 'sketch' looks similar to this:

Code: [Select]echo off
setlocal
:start
cls
echo Type in something (No more than 8 letters long)
set /p option=

:loop
 if defined option (set option=%option:~1%& set /a length += 1 & goto loop)
 if %length% GTR 8 goto :toohigh
 
:toohigh
echo Too many letters
pause >nul
goto :start

:continued
echo Ok
pause >nul
exit

The problem is that when the amount of letters IS lower than 8, it just continues (LIKE i wanted) but not to a specific place. How would you do that? Like if %length% is lower/equal than 8 then goto :continued.

Also another problem is if they screw up (more than 8 letters) i want it to go back to :start and try it again. But when i do this, no matter what i type in, it always goes to :toohigh and says too many letters even if it obviously isn't. Please help :/


-----EDIT----- Larrylong helped me on this and it solved both of my problems.
It was just changed a little but it works
Code: [Select]echo off
:start
cls
echo Enter what you want but no more than 8 letters.
set /p MyVar=
set A=%MyVar%
set length=0
:loop
if defined A (set A=%A:~1%&set /A length += 1&goto loop)
set /a greater=8
if %length% GTR %greater% goto :toohigh
if %length% LSS %greater% goto :continued



:toohigh
cls
echo Too many letters...
echo.
pause >nul
goto :start

:continued
cls
echo Good Job :D
pause >nul

The only thing that really changed was that he added "set length=0" and
if %length% GTR %greater% goto :toohigh
if %length% LSS %greater% goto :continued

Thanks anyway Sidewinder
Quote from: shanked on November 24, 2010, 06:15:07 PM
The problem is that when the amount of letters IS lower than 8, it just continues (like i wanted) but not to a specific place. How would you do that? Like if %length% is lower/equal than 8 then goto :continued.

Place a goto immediately beneath the if line that goes to "toohigh". for example:
Code: [Select] if %length% GTR 8 goto toohigh
 goto continue
Quote from: BC_Programmer on November 24, 2010, 06:25:43 PM
Place a goto immediately beneath the if line that goes to "toohigh". for example:
Code: [Select] if %length% GTR 8 goto toohigh
 goto continue

Omg i should have known that 
Thanks though Quote from: shanked on November 24, 2010, 06:15:07 PM
Thanks anyway Sidewinder

I'm just glad that Larry was able to help you out. Larry has been able to use his multi-faceted personality to help numerous posters. He was wanted by many other forums, so we were truly honored when Larry chose CH.

It gives Thanksgiving a whole new meaning.

 
360.

Solve : Some folders aren't affected by move command?

Answer»

Hello.  I am having a problem with something I'm trying to do with a BATCH file.  I want to delete most of the files, excluding a few, from a folder called Plugins.  Then I want to move all of the folders (and their contents) from a directory at the same level as Plugins, Plugins.nonpacked, to the Plugins folder.  That STEP is where it's failing.  There are five folders within Plugins.nonpacked, named "BATs, Lots", BSC, Dependencies, PEGPROD, and SFBT.  When the batch file tries to move all of these folders to my Plugins folder, it moves most of them but leaves behind BSC and PEGPROD with a "The system cannot find the file specified" or similar error for each of them.  I have also tried moving these folders individually and using XCOPY to copy them, which results in a message of "0 file(s) copied".  These folders are different from the other three because they contain no files directly within them, but have only subfolders with files inside of those.  The three folders that succeed in moving have files in their root directories, as well as subfolders.  Here is the batch file:

Code: [Select]cd Plugins
attrib "BATs, Lots.dat" +r
attrib Dependencies.dat +r
attrib BSC.dat +r
attrib SFBT.dat +r
attrib PEGPROD.dat +r
attrib "BATs, Lots-*.dat" +r
attrib Dependencies-*.dat +r
attrib BSC-*.dat +r
attrib SFBT-*.dat +r
attrib PEGPROD-*.dat +r
del /s /q *.*
FOR /D %%a in (*) DO rmdir /s /q "%%a"
attrib "BATs, Lots.dat" -r
attrib Dependencies.dat -r
attrib BSC.dat -r
attrib SFBT.dat -r
attrib PEGPROD.dat -r
attrib "BATs, Lots-*.dat" -r
attrib Dependencies-*.dat -r
attrib BSC-*.dat -r
attrib SFBT-*.dat -r
attrib PEGPROD-*.dat -r
cd ..\
for /d %%b in (plugins.nonpacked\*) do move "%%b" "plugins"That is a lot of work. Do you really need to do this?
Or is this just a case of you want to see if it can be done?
Are you short on disk space?
Is this something you need to do an a regular basis?
Do you have an NETWORK drive  for backup?
Windows and DOS do not do well at moving large blocks for files and folders with exemptions and attribute issues..
But making a copy or backup over a network works fine. Even monster volumes
As for me, I would just copy to a backup volume. Then delete everything and restore just what I wanted. No batch file needed.
Please explain - why that would not work for you? Quote from: moonraker0 on November 23, 2010, 10:30:47 PM

These folders are different from the other three because they contain no files directly within them, but have only subfolders with files inside of those. 

When you used XCOPY, did you use the /E switch?Geek-9PM:  Yes, this is something I do frequently, and I became TIRED of doing it all manually.  This batch file is not complete; after all those tasks execute, I also want to RUN an application, and when that's done I want to move the files that were just moved in to the folder back to Plugins.nonpacked.  After that is done, the batch file should copy files from another folder, Plugins.alwaysloose, back into Plugins.

BC_Programmer:  Yes, I forgot to mention that I did use the /e switch when I tried XCOPY.
361.

Solve : Difference between CMD and Command.com??

Answer»

What exactly is the DIFFERENCE between CMD and COMMAND.COM? is command.com used solely for 16-bit PROGRAMS? or is there more to it than that?

Thanks Quote

What exactly is the difference

You ain't going to get that answered here; life is too short and you NEED to do some independent reading. See links below. There are a zillion online references and those are only a tiny selection.

Cmd.exe is the 32 bit Windows NT family command interpreter; command.com is the 16 bit MS-DOS command interpreter. Cmd.exe has a much larger set of commands and most of the ones it shares with command.com have more features.

http://ask-leo.com/whats_the_difference_between_commandcom_and_cmdexe.html

http://en.wikipedia.org/wiki/Batch_file

http://www.netikka.net/tsneti/http/tsnetihttpprog.php#cmdscript

362.

Solve : Alphebet to Number?

Answer»

Is there a way to assign a character like "a" a number like "1"? So that the USER can input a letter, the batch file will add a number and it will out put another letter that is equal to the two values added?

for EXAMPLE
a=1
b=2
c=3

they input "a" and then the batch file adds two. So the batch file would output "c" because 1+2=3

ThanksTry this:

Code: [Select]echo off

set /P choice=input letter:


if %choice% EQU a set result=1
if %choice% EQU b set result=2
if %choice% EQU c set result=3
if %choice% EQU d set result=4
if %choice% EQU e set result=5
if %choice% EQU f set result=6
if %choice% EQU g set result=7
if %choice% EQU h set result=8
if %choice% EQU i set result=9

set /a result= %result%+2


if %result% EQU 1 set FINAL=a
if %result% EQU 2 set final=b
if %result% EQU 3 set final=c
if %result% EQU 4 set final=d
if %result% EQU 5 set final=e
if %result% EQU 6 set final=f
if %result% EQU 7 set final=g
if %result% EQU 8 set final=h
if %result% EQU 9 set final=i
if %result% EQU 10 set final=j
if %result% EQU 11 set final=k

echo %final%
pause

Does this work out for you?Yes, thankyou. It really helped!

363.

Solve : Batch program-DOS?

Answer»

I have a DOS batch program that opens 80+ windows with different URLS.  Is there a code that can check the status of the IE WINDOW (if it FAILED to open the URL - proceed to the next URL and print a log of the failed URL)?  Would appreciate any help you can provide.  Thank you. Quote

I have a DOS batch program that opens 80+ windows with different URLs

Opens them how? With Internet Explorer? Ping? What method?

On a notepad that was saved as a batch file:
echo Start test of 3  URLs

start iexplore.exe http://www.yahoo.com
echo yahoo started

start iexplore.exe https://www.google.com
echo google started

start iexplore.exe https://www.gmail.com
echo gmail started

echo Completed test of 3 URLsI would use ping and check the errorlevel. Having 80 windows open will be a royal pain in the *censored*.
Is there an errorlevel number I have to check for?  I agree about this being a pain but it does relieve me from CLICKING 80+ times on a hyperlink  .  Thank you for the suggestion, I'll check for code examples of pinging and errorlevel checking. Quote from: newbie8 on November 24, 2010, 11:54:37 AM
Is there an errorlevel number I have to check for? 

for your method, no.

A errorlevel is RETURNED when a program exits. Never before. So while the "start" program could give you back a errorlevel, it couldn't get that errorlevel from Internet Explorer since it's still running, and hasn't closed. Quote from: BC_Programmer on November 24, 2010, 12:09:03 PM
for your method, no.

A errorlevel is returned when a program exits. Never before. So while the "start" program could give you back a errorlevel, it couldn't get that errorlevel from Internet Explorer since it's still running, and hasn't closed.

Quote from: Me
I would use ping and check the errorlevel. Having 80 windows open will be a royal pain in the *censored*.
Thanks for all your feedbacks and suggestions.  I will try the ping method.Is there a way to find out on DOS command when my internet connection is slowing?
364.

Solve : Choosing random numbers without repeats.?

Answer»

How could you make a batch file choose random numbers (for example 1-20) without repeating each other? Also, how can it 'detect' that it picked ALL of the numbers then go somewhere else (goto :blank)?

I know how to choose random numbers:
Code: [Select]echo off
:1
cls
set /a R=%random%%% 20 +1
echo %R%
pause >nul
goto 1

But theres some problems in this. It repeats numbers, and doesn't go anywhere if/when it detects all of the numbers have been used (the two main points in the BEGINNING)

Please help   

Quote

It repeats numbers, and doesn't go anywhere if/when it detects all of the numbers have been used (the two main points in the beginning)

It repeats numbers because past performance is no indicator of future results. Each resolution of random is an independent event and has no "memory" of what numbers were chosen previously.

I'm not seeing in your code where it detects when all the numbers have been used. You will need to keep a history of numbers displayed and if there is a duplicate, re-randomize until a non-duplicate is found.  You could use an array in Powershell to hold the history or the dictionary object in VBScript.  Other script languages have similar features.

Good luck. 

Note: using pause > nul without any indication to the user of what to do, will not win you any gold stars. The way I'd do it in a more capable language would be to create an array of all the items that can be selected, and when a random item is chosen, choose an index into that array randomly, use the value in the index as the random value, and then remove the item from that list.

This makes choosing a random number linear with regards to how many items have been previously selected, whereas if you were to store each selected item, you would have to go through all the stored items and make sure it's not the new choice; what this would mean is that, if you had 100 values and you  had already chosen 99, whereas the method I propose would instantly give you back that last number, the more "brute-force" approach would probably take a very long time to finally come up with the only POSSIBLE solution. Code: [Select]echo off
setlocal enabledelayedexpansion
set maxnum=20
if exist AlreadyChosen.txt del AlreadyChosen.txt
:loop
set /a RandNum=%random%%%%maxnum%+1
set alreadychosen=0
if exist AlreadyChosen.txt for /f "delims=" %%A in (AlreadyChosen.txt) do (if "%%A"=="%RandNum%" set alreadychosen=1)
if %alreadychosen% equ 0 (>> AlreadyChosen.txt echo %RandNum%)
set NumbersStored=0
for /f "delims=" %%A in (AlreadyChosen.txt) do set /a NumbersStored=!NumbersStored!+1
if %NumbersStored% lss %maxnum% goto loop
echo Have now chosen every single number between 1 and %maxnum% once each.

times (3.0 GHz AMD Phenom II, 7200 rpm HDD)

Code: [Select]maxnum       seconds
10           0.09 sec
20           0.25 sec
100          6.35 sec
200          32.48 sec
500          201.51 sec


Quote from: Salmon Trout on December 02, 2010, 12:04:26 PM
Code: [Select]echo off
setlocal enabledelayedexpansion
set maxnum=20
if exist AlreadyChosen.txt del AlreadyChosen.txt
:loop
set /a RandNum=%random%%%%maxnum%+1
set alreadychosen=0
if exist AlreadyChosen.txt for /f "delims=" %%A in (AlreadyChosen.txt) do (if "%%A"=="%RandNum%" set alreadychosen=1)
if %alreadychosen% equ 0 (>> AlreadyChosen.txt echo %RandNum%)
set NumbersStored=0
for /f "delims=" %%A in (AlreadyChosen.txt) do set /a NumbersStored=!NumbersStored!+1
if %NumbersStored% lss %maxnum% goto loop
echo Have now chosen every single number between 1 and %maxnum% once each.

Wow that's almost exactly what i wanted/needed. Thanks a lot But one little tweak i hope you can do is not make a .txt file with the numbers, but actually show them instead (on batch screen).

Also, if you could make it show on the batch screen, is there a way to put a pause between each number? For example it picks a random number from 1-20 and shows it, and when you press any key it will show the next number and so on.I will do some more tomorrow; it is 11 PM now and I am working tomorrow; look for a post in around 18 hours
Code: [Select]echo off
setlocal enabledelayedexpansion
set maxnum=20
if exist AlreadyChosen.txt del AlreadyChosen.txt
:loop
set /a RandNum=%random%%%%maxnum%+1
set alreadychosen=0
if exist AlreadyChosen.txt for /f "delims=" %%A in (AlreadyChosen.txt) do (if "%%A"=="%RandNum%" set alreadychosen=1)
if %alreadychosen% equ 0 (
>> AlreadyChosen.txt echo %RandNum%
echo %RandNum%
echo press a key for another number
pause>nul
)
set NumbersStored=0
for /f "delims=" %%A in (AlreadyChosen.txt) do set /a NumbersStored=!NumbersStored!+1
if %NumbersStored% lss %maxnum% goto loop
echo Have now chosen every single number between 1 and %maxnum% once each.
Thanks a lot! Works great!I have been playing around with this. I believe any non-random-access method will slow down exponentially as the max number increases. This is what you might expect. With a sequential access method the more numbers you have already chosen, the longer it will take on average to verify that each random number chosen is a new one. The method repeatedly scanning a single text file is quite slow. Next I tried creating an empty string VARIABLE and appending each chosen number to it, bracketing each one with separators e.g. 30 19 2 15 and using FIND separator%randnum%separator to decide if a new random number was already chosen. This is dramatically slower than the previous method for smaller values of maxnum but there is a point where it gets faster (on my system it is occurs somewhere between 250 - 500 with the disk I am using.) Finally I tried creating a subfolder and creating a small file in it named for each number chosen, e.g.

echo.>tempfolder\%randnum%

Then you can exploit file system random access and use IF EXIST tempfolder\%randnum% to see if a new number has already been chosen. This is much faster than either of the previous methods.

Time in seconds

Maxnum    textfile   string  filenames
 10        0.07       0.11     0.09
 50        1.01       5.32     0.35
100        4.18       9.88     0.73
250       26.65      38.07     1.80
500      145.46      86.79     4.34

[edit] I can't believe I have spent an hour on this! It underlines that for anything more than toy stuff, you need to learn a proper programming language.




I found this in the snippet CLOSET. Originally written in VBScript using the dictionary object, this uses a compound naming convention for the variables. Basically it is another approach to the solution.

The first part of the variable name is the word slot. The second portion is the random number generated as is the value of the variable. This produces variables such as slot.20 with a value of 20 or slot.15 with a value of 15. Using such a scheme allows the code to simply check if the variable is defined and eliminates the file system processing.

As previously pointed out, the code slows down as the pool of unused random numbers shrinks. I made the code generic by allowing the user to enter the min and max numbers of the number range. I also eliminated the PROMPT to get the next number, but the code is remarked out and can easily be reactivated.

Code: [Select]echo off
::
:: No error check that max num is greater than min num
::
setlocal

set /p intLowNumber=Enter Minimum Number:
set /p intHighNumber=Enter Maximum Number:

set /a intMin=%intLowNumber%
set /a intMax=%intHighNumber%
set /a count=%intLowNumber%

:loop
  if %count% GTR %intHighNumber% goto :eof
  set /a rnd=%random% %% (%intHighNumber% - %intLowNumber% + 1) + %intLowNumber%
  if not defined slot.%rnd% (
    set slot.%rnd%=%rnd%
    set /a count+=1
    echo %rnd%
    rem echo Press A Key For Next Number
    rem pause>nul
  )
  goto loop

 Sidewinder's method is fastest by far.
365.

Solve : SImple enough code giving error... any ideas??

Answer»

So if the user types the NAME of the script it should just GO to the start sub method but if they type Help it should give them a help menu

"whatever.bat Help" should go to help menu

"whatever.bat" should just run the program

Code: [Select]echo Off

set Input=%1%
echo %input%
pause
if %Input%== goto :start
if %Input%==Help goto :Help
I get a error message stating "goto was unexpected at this time."

I have tried a couple DIFFERENT combination of codes including :

if %Input%== NULL goto :start

or

if %Input%== {} goto :start

With no avail... anyone got any ideas of what I am doing wrong or what I could do to make it WORK right?

ThanksThanks to whomever sent me a message here is the code that worked:

Code: [Select]IF "%1"=="" goto :CONTINUE

set Input=%1

if %Input%==help  (
goto :help
)
goto :continue



:continue
Code: [Select]echo Off

set Input=%1
echo %input%
pause
if %Input%!==! goto :start
if %Input%==Help goto :Help

366.

Solve : question on task schedules log file?

Answer»

Hi,

I have a question REGARDING the DOS batch file. I have a couple of batch FILES (.bat) and added them to the task schedules that will run them at every two hours. I have also had a perl-based file (.pl) scheduled to run every night.

When I checked on the schedule log file, i saw the following
"backup_data.job" (LM2FS(Data).bat)
   Result: The task completed with an EXIT code of (1).
"backup_mails.job" (LM2MS(Mail).bat)
   Result: The task completed with an exit code of (1).

However, I GOT a different result for perl-based file
"rebuildspamdb.job" (rebuildspamdb.pl)
   Result: The task completed with an exit code of (0).

I wonder what it MEANS if it says the task completed with an exit code of (1) and the task completed with an exit code of (0).

Any help would be greatly appreciated.

Thank you in advance

367.

Solve : delete duplicates in text file?

Answer»

I have a text file with hundreds of e-mail addresses in it (separated by semi-colons) - no, NOT for spamming! I want to get rid of duplicate e-mail addresses within the file so if I broadcast a message to those on my list, I won't annoy anybody by sending it two or three times. Any suggestions would be welcomed, as I have tried everything including a script from MS Technet which I could not get to run.Are you saying the file has MULTIPLE email addresses separated by semi-colons on each line or one address per line with a semi-colon at the end.

In either case, one solution would be Excel (if installed). You can use it to filter unique records, put them on another sheet, then save the sheet as a text file. Excel would require a lot of cut & paste if more than one address per line.

If you know any scripting language, this can be scripted without too much hassle.

Generally the scripts from MS Techet teach technique and require some editing before they will run on the LOCAL machine.

If you still have problems, post the script you got from Technet and someone can probably help you.

Many thanks for the REPLY. The e-mail addresses are all on a "continuous line" in notepad separated by a semi-colon. I was looking to SIMPLY copy & paste into an outlook e-mail message when done. Excel limits the import to about 65 out of hundreds, so that doesn't work. The following script which I can't get to work is from Technet at:

www.microsoft.com/technet/scriptcenter/resources/qanda/apr05/hey0413.mspx


Const ForReading = 1
Const ForWriting = 2

Set objDictionary = CreateObject("Scripting.Dictionary")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile c:\newletter-duplicates-.txt
   ("c:\scripts\namelist.txt", ForReading)

Do Until objFile.AtEndOfStream
   strName = objFile.ReadLine
   If Not objDictionary.Exists(strName) Then
       objDictionary.Add strName, strName
   End If
Loop

objFile.Close

Set objFile = objFSO.OpenTextFile c:\newletter-clean.txt
   ("c:\scripts\namelist.txt", ForWriting)

For Each strKey in objDictionary.Keys
   objFile.WriteLine strKey
Next

objFile.Close

Well you could open the file in Word.  Do a search and replace on the ";" and replace it with ";" plus the carriage return character.  This would give you a list in a single column that you could open and sort with Excel.  Then you could manually remove the duplicates from the sorted list.  Excel will then allow you to save the file as a text file.

If you wanted it back to a single line list you could reverse the search and replace using Word.Good idea, but I tried it with no success. There appears to be no way of geting an "enter" or "carriage return" into the replace cell in the word repalce window. You can insert the ; but if you hit enter it starts the replace processSure there is.  When you do the replace look on the bottom of the replace window, you will see a "more" button, click it, then click the "special" button, and select "manual line break"

See your other post on the Windows board for an automated  solution for this.

Gussery - thanks, I never saw the drop down. I will try again.

Sidewinder - I posted to you on the other board.

Many, many thanks to you both for your input and your good natures!!Here is a good tool to delete duplicate FILES
www.duplicateFilesDeleter.comHe left 5 Years ago....i doubt he'll see your Post. Quote from: patio on November 28, 2010, 08:00:53 AM

He left 5 Years ago....i doubt he'll see your Post.

And he wasn't even asking about duplicate files. And the link posted was for "free-trial" payware.

368.

Solve : Unable to get IF condition work in batch script?

Answer»

Below is my code

echo off
echo option CONFIRM off > testupload.txt
echo open winscp >> testupload.txt
echo close >> testupload.txt
echo exit >> testupload.txt
winscp /script=testupload.txt /ini=winscp.ini /log=log1.txt > sri_test.txt
findstr /I /L /M "Still" sri_test.txt > out.txt
echo sri_test.txt >> out.txt
For /f "TOKENS=* delims= " %%a in (out.txt) do set myvar=%%a
echo %myvar%
IF "%myvar"=="sri_test.txt" sri.bat


The issue is if condition is executed irrespective of  %myvar value. I am hardcoding %myvar to "sri_test.txt", still it is not letting me in. What's wrong with DOS?Pls help Quote

Code: [SELECT]IF "%myvar"=="sri_test.txt" sri.bat

Use "%myvar%" not "%myvar"





As foxidrive told you this in alt.msdos.batch, Even when you correct that typo the code will *always* execute sri.bat because you are echoing it into the file and your for loop will set myvar to be the last line of the file.






369.

Solve : replacing all '.' in 315k text file with other text. Cant do with replace =(?

Answer»

I have a text file that is 315k in size containing a query from a database that I dumped out to a text file. I have added '.' (periods) into the 38000 lines of info and want to replace this '.' with other ascii text without any spaces. I tried doing this with notepad replace and it completed about 10 lines and then notepad became unresponsive. I am guessing that 38000 lines is too much for notepad and I could BREAK it into smaller chunks for notepad to chew on, but figured I'd check here first to see if anyone knew of a way to do this using batch which may not crash LIKE window$ notepad on huge text files.

The original query was just raw text and in order to add text leading into each item on each line, I wrote a quick macro using jitbit macro creator to place a "." (period) then down arrow and left arrow and repeat with a goto statement. This worked perfect and took a while to chug through the 38000 lines at 15MS per line to execute with 5ms delays that i added.

My plans were to use the periods as tags for notepad to replace the periods with other text later on that is about 20 characters in length that ends with = and bound tight with the DATA on each line. Then i was going to run this 38000 lines with the repeated instructions ending in = before each individual item and have that run for a few hours to chug out an analysis.

Without a unique marker tag, you cant use the find and replace all feature, so I planted a period before each item and was hoping after that to just replace all periods with the 20 character instruction that ends in = before the data on each line, save it and then run it through the final process.

Any suggestions if batch is unable to find all "." and replace with "merge_data_xxxxxxxxxx="

ThanksA VBSCRIPT should do the job:

Code: [Select]Dim Inputfile
Dim Outputfile
Dim SearchFor
Dim ReplaceWith
Inputfile = WScript.Arguments(0)
OutputFile = WScript.Arguments(1)
SearchFor = WScript.Arguments(2)
ReplaceWith = WScript.Arguments(3)
WScript.Echo "Using Input file:" + Inputfile
WScript.Echo "Using Output file:" + Outputfile
WScript.Echo "Searching for:" + SearchFor
WScript.Echo "Replacing with:" + ReplaceWith
Dim FSO
Dim InStream,OutStream
Dim LineRead
Set FSO = CreateObject("Scripting.FileSystemObject")
Set InStream = FSO.OpenTextFile(Inputfile)
Set OutStream = FSO.CreateTextFile(OutputFile)

WScript.Echo TypeName(InStream)
Do Until InStream.AtEndOfStream
'Read a line from the input file.
LineRead = InStream.ReadLine()
'perform the replacement.
LineRead = Replace(LineRead,SearchFor,ReplaceWith)
'write to the output file.
OutStream.WriteLine LineRead



Loop
InStream.Close()
OutStream.Close()

execute like so:

Code: [Select]CScript replacer.vbs inputfile.txt outputfile.txt . "Replaced text"
Code: [Select]echo off
setlocal enabledelayedexpansion
if exist output.txt del output.txt
set SearchFor=.
set ReplaceWith=merge_data_xxxxxxxxxx=
for /f "delims=" %%A in (input.txt) do (
set line1=%%A
set line2=!line1:%SearchFor%=%ReplaceWith%!
echo !line2!>>output.txt
)

Cool I will give that a shot. Many Thanks!!

370.

Solve : Batch chat box??

Answer»

Hello! I am having trouble creating a BATCH chat box. You know.. when you can chat with your OWN COMPUTER!! :O ;d
This is what i have done for now:
echo off
:startgame
cls
echo Hi wazup! Who are you?
set /p name=
echo OK, %name%! Say something!
set /p chat=
if %chat% == somehing echo something EH?
So here is my trouble..
How can I make something like this:
if %chat% NOT == somehing echo What? I didnt undestand.Ok i added something like this :
goto :LOOP
:LOOP
set /p chat=
IF "%chat%"=="" (
ECHO Nothing is entered
GoTo :LOOP
)
IF /I "%chat%"=="Hi" (
echo Hello
Goto :loop



C:\test>type chat.bat
echo off
setlocal enabledelayedexpansion
set chat=echo chat=%chat%
:loop
echo enter greeting?
set /p chat=
echo chat=%chat%
IF "%chat%"=="" (
echo Nothing is entered
goto :loop
)
if  "%chat%"=="HI" (
echo Hello
set chat=goto :loop
)
echo Hasta La Vista
echo Do you want to stop(Y/N)
echo Use UPPER case Y
set /p ans=
if %ans%==Y goto :end
set chat=goto :loop
:end
echo Bye
 
Output:

C:\test> chat.bat
chat=
enter greeting?

chat=
Nothing is entered
enter greeting?
HI
chat=HI
Hello
enter greeting?
How are you?
chat=How are you?
Hasta La Vista
Do you want to stop(Y/N)
Use upper case Y
n
enter greeting?
Good Morning
chat=Good Morning
Hasta La Vista
Do you want to stop(Y/N)
Use upper case Y
Y
Bye

C:\test>

371.

Solve : Copying files marked as "system files"?

Answer»

I'm having issues copying some files. I've tried xcopy using the /h parameter but it returns "File not found" though I can see the file after changing directory to the folder and using the "dir /s" command. So the file is there, but it wont copy the file. I tried using a generic to copy everything in file and all that copies is "desktop.ini" nothing else. Quote from: DarkendHeart on September 12, 2010, 10:21:55 PM

though I can see the file after changing directory to the folder and using the "dir /s" command.

dir /s will view the contents of the folder and all it's subfolders. It doesn't see hidden files.

Therefore the desktop.ini file you are seeing is probably a non-hidden file in a subdirectory of the folder in question.

can you see the file with a dir /a?No I cant, but when I physically go into the folder it has no other folders in it. I can see the file I want to copy, and I can drag and drop it over like that but for what ever reason xcopy says it's not there. Quote from: BC_Programmer on September 12, 2010, 10:24:59 PM
can you see the file with a dir /a?

Quote from: DarkendHeart on September 12, 2010, 10:34:33 PM
No I cant


The file has the system attribute as well as the hidden attribute.

I just tested it by creating a file with the hidden attribute. Xcopy /h found the file fine. However if I also added the system attribute xcopy reported "file not found".... despite the /H switch description specifying it would copy hidden & system files.

Explorer was able to copy/paste the file and drag and drop it properly.

That's pretty much where I'm at. I'd like for xcopy to do the copying instead of having to drag and drop since I'll be adapting it to copy file extensions instead of just one file. Is there anyway around it? Maybe a command that could remove it's system attribute so I can copy it? It seems though once I remove it from the source folder it loses is hidden/system attributes and I can find it again with xcopy. Could I do a mass move and just dump everything to a temp folder so xcopy can find it and then start copying? Assuming there is a command that isn't limited by the system attribute.I think I solved the problem. What I ended up doing was copying everything out of the parent folder of the folder that had the file(s) I needed in it to a temp location. After doing that I navigated into that folder and was able to copy the file out of that folder to the final location. Kind of BACK assed I know, but it seems like it's the only way that would work. Also why the files weren't copying out of the folder to begin with and why I was only getting "Desktop.ini" instead of everything else is because the system has them marked as "empty" files so I had to add the "/e" switch with the "/h" switch for xcopy to move them.

Now the problem is deleting the files from the temp directory.
It says they're deleted but they aren't.So it wont let me delete them as it's a "read-me only" attribute. Though using the attrib -r /s /d command doesn't remove it's read-me only attribute. I even tried...
for /r %d in (.) do attrib -r %d /s /d
... and it appears that it works but never removes the read-me statues. Even right clicking the folder and going into properties and unchecking read-me only still does nothing. It applies and doesn't have any error, but never changes the attributes. Though I can click it and hit delete and that works, but the del or erase command will not delete it.Any ideas? I can traverse into every single folder inside the temp file and delete all the files out of those but the folders them selves will not delete. After doing some testing it seems for w.e reason I cant use the del command if the folder has a read-only attribute. Though I cant remove that attribute either. This is frustrating as I cant seem to delete ANY folder that has a read-only attribute set but they system wont let me change it. I am the admin on the machine and the command line is running as the admin, yet I still cant remove the read-only attribute. I can remove System and Hidden attributes but not read-only. It seems to just be some kind of issue with windows not really recognizing "read-only" attribute though that attribute prevents dos from deleting it. Sadly the work around that was mentioned on the Microsoft's support site doesn't work.Windows 7 is not fit for purpose and should never have even entered Beta.

It employs Junctions and that are supposed to give a form of backward compatibility with older applications written for XP.

Some of them are black holes.  You can put files in them, but you cannot get them back, and you cannot read them or delete them.  It is a fiasco.

I have counted 44 Junctions in Windows 7,  most of those I wanted are blackholes

Run CMD.EXE and past this into the window.

Code: [Select]CD \
echo %TIME% > "%USERPROFILE%\Application Data"\ALAN_LOST
DEL "%USERPROFILE%\Application Data"\ALAN_LOST
echo %TIME% > "%APPDATA%"\ALAN_KEPT
echo %TIME% >> "%USERPROFILE%\Application Data"\ALAN_LOST
TYPE "%USERPROFILE%\Application Data"\ALAN_LOST
TYPE "%APPDATA%"\ALAN_KEPT
TYPE "%APPDATA%"\ALAN_LOST
DEL "%APPDATA%"\ALAN_KEPT
DEL "%APPDATA%"\ALAN_LOST

Nothing strange under XP,  no errors - nothing to see her - move along.
Under Windows 7 Ultimate I got errors and black-holes as per image attached.

Alan


[recovering disk space - old attachment deleted by admin] Quote from: ALAN_BR on September 19, 2010, 03:55:34 PM
Windows 7 is not fit for purpose and should never have even entered Beta.
There is nothing wrong with windows 7. Or Vista, for that matter.

Quote
Under Windows 7 Ultimate I got errors and black-holes as per image attached.
Works fine here:




Where is this "black hole"? the Application Data folder redirects to %appdata% which is usually %userprofile%\AppData\Roaming. As you can see the Type command worked perfectly fine, as did both redirects. The Access Denied error is for a very good reason, since  write Access to the "Application Data" junction is only allowed by some programs (usually those with a compatibility mode set to XP or earlier). If that wasn't the case, how many "power" users do you think would encounter it, be ABLE to look inside the folder, and decide "well GOLLY GEE! I already have all those files in %appdata%... DELETE"

only to find they just deleted %appdata%. Would they be pleased? *censored* no. They just deleted all their documents.

There is no capability for "data loss" here, as you claim. In fact, the opposite is true.You misunderstand.
I never said "data loss" but
"Some of them are black holes.  You can put files in them, but you cannot get them back"

I mean that you cannot access the files by using the same path used for storing them.
This is nothing but "data loss" for people who do not know where to look for them.

This BlackHole problem I was unaware of until it hit me.
There are many others who have yet to suffer this aggravation.

Your "...\Application Data" is a Blackhole.  You can put a file in, but you cannot get it back.
It is a SciFi type of blackhole with a wormhole to a distant galaxy, or in this case to a destination that is fully accessible to all read and write operations via the path
"...\Appdata\Roaming",
BUT IT IS ONLY ACCESSIBLE for those who look in the correct place,
and is totally lost for those who have downloaded a script that uses XP compliant paths.

What I have learnt from the Internet is that people lost everything because they believed original documentation that indicated a Junction was like a short-cut which could be safely deleted without harming the contents of what it re-directed to.

Microsoft did not correct their enormous mistake, and instead admitted the error BUT recommended that Junctions should be protected from accidental deletion by the use of CACLS.

I have used CACLS to inspect the permissions and restrictions of a sample from the 44 Junctions scattered around Windows 7, and find significant differences between them.

You have what could be a good point about protecting "Power Users",
but I would counter with :-

1.  Although a Junction may protect against reading or deleting a file, it does not protect against appending a file, and presumable may permit a file to be written even if it over-writes another file.
Interesting example encountered at :-
http://forum.piriform.com/index.php?showtopic=29618
With a reinstall of Vista that resulted in an extra folder called "Windows Old", a CCleaner user found that  CCleaner was prepared to delete music from to delete "Windows Old" and he let it happen.
He lost much of his real music that he treasured.
He found CCleaner did no such harm with a normal delete (which Junctions tend to block)
but his use of SECURE delete meant the files were over-written and lost.
I assume that what he saw as being in "Windows Old" actually encountered a Junction that was frozen at some place in "Windows"
The "nanny mode" of protecting against loss of data via Junctions may be fool-proof, but is not "Power user" proof ! !

2.  Any self proclaimed power user that meddles with things he does not understand needs to learn better, and even XP will punish him if he removes duplicates that are genuinely independent duplicates but XP still expects to find them.
I have a total of 471 instances of Desktop.ini within 4 partitions.
I wonder what Windows would look like if I removed 470 of them ! ! !

3.  I strongly suspect that power users are not fully protected.
Not all Junctions are Blackholes, some give full bidirectional access,
which means that DEL will delete a destination file and RD will delete a destination folder via a path that includes a Junction, so I suggest these are points of vulnerability to a meddlesome "Power User".
I guess the variation is something to do with M.$ not being sure what to do with CACLS.
e.g.
V:\W7_OOPS>CACLS "C:\Documents and Settings\Alan\Application Data\"   | FIND ":"
C:\Documents and Settings\Alan\Application Data Everyone:(DENY)(special access:)
                                                NT AUTHORITY\SYSTEM:(OI)(CI)(ID)F
                                                BUILTIN\Administrators:(OI)(CI)(ID)F
                                                Alan-Laptop-W7\Alan:(OI)(CI)(ID)F
or
V:\W7_OOPS>CACLS "C:\Users\Alan\AppData\Local\"   | FIND ":"
C:\Users\Alan\AppData\Local NT AUTHORITY\SYSTEM:(OI)(CI)F
                            BUILTIN\Administrators:(OI)(CI)F
                            Alan-Laptop-W7\Alan:(OI)(CI)F
or
V:\W7_OOPS>CACLS "C:\Users\Alan\Local Settings\Application Data\"   | FIND ":"
Access is denied.
or
V:\W7_OOPS>CACLS "C:\ProgramData\"   | FIND ":"
C:\ProgramData NT AUTHORITY\SYSTEM:(OI)(CI)F
               BUILTIN\Administrators:(OI)(CI)F
               CREATOR OWNER:(OI)(CI)(IO)F
               BUILTIN\Users:(OI)(CI)R
               BUILTIN\Users:(CI)(special access:)
or
V:\W7_OOPS>CACLS "C:\ProgramData\Application Data\"   | FIND ":"
C:\ProgramData\Application Data Everyone:(DENY)(special access:)
                                Everyone:R
                                NT AUTHORITY\SYSTEM:F
                                BUILTIN\Administrators:F

When Comodo Security is upgraded it may need un-installation of the old before the new,
and the new may be blocked if residues remain due to sundry glitches, so various users have posted scripts that seek and destroy the residues.
Those scripts work on XP for some people, but failed for me due to permissions issues.
I added "error checking" to confirm successful removal or report specific problems that needed manual intervention.
Perfection at last on XP.

Before final release I checked that all was well on W7 and found disaster.
There were "residues" which I deliberately planted to ensure correct detection and removal or reporting.
They were not detected.
Even using %USERPROFILE%\etc... or %APPDATA%\etc... they could not be detected if the \etc... went through another Blackhole type junction - IF EXIST could not see them, CACLS had no access, DEL could not touch them.

This aggravation has caused me to build up a full head of steam.  Sorry about that.

The original start of this thread was that the O/P knew certain files existed in a certain place but he could not copy them.  This resonated very strongly with the problem I have suffered, and after checking his profile and seeing that the OP use W7 I thought that BlackHole junctions might be the cause depending upon what paths he was using, so I posted what I thought might be useful to him.

I have much more to say and discuss, and questions to ask.
Thank you for your information on compatibility mode,
I have never needed it before and will investigate how this might affect CMD.EXE scripts.

I do not wish to be barred by a moderator for hijacking the OP's topic,
and suggest we take this outside to settle it ! !

I propose to start a topic in the Windows 7 forum when I get a few other urgent things done,
and will post here a quick invitation to join me there when I have organized my evidence against Junctions.

Regards
Alan
Alan thank you very much for posting what you did, I would definitely not classify this as high-jacking as this was very insightful. I never knew such things could and do happen. That would probably explain why I cant delete them using that command.

Do you know of any kind of workaround or some way I may be able to del/copy them?

I can successfully copy them but I have to copy the parent folder the files are in to a secondary file which I can use the attrib command to remove their system/hidden attributes. Though sadly, windows does not let me delete these new folders using the del command. I know these copied folders are standalone from the others as the original maintains it's attributes and files inside of it. Where as the copied folders I can change their attributes(excluding read-only), and I can delete the files from those folders but not the folders them selves.XCOPY /H
That is like Copy but will deal with Hidden and System files should be included.
You will see lots of options by
XCOPY /?

That may be all you need, depending upon what paths are involved,
but Junctions can give all sorts of problems.

My favorite resource is
http://wapedia.mobi/en/Environment_variable?t=5.#5.
The top item shows the environment variable %APPDATA%
and the real destination for both XP and Vista/W7
It is far better to access via %APPDATA% than the XP equivalent of C:\Documents and .......
The XP equivalent will in W7 be redirected by Junction(s) but with restricted permissions.

This freeware will scan the system and find and report all junctions.
http://rekenwonder.com/linkmagic.htm
N.B. the scan took LONGER on my machine than a coffee break,
so I took a lunch break and it finished before I ended my meal.

It reports the location of the Junction and where the REAL destination is. e.g.
Code: [Select]==================================================
Junction point    : C:\Users\Alan\Application Data\
Destination       : C:\Users\Alan\AppData\Roaming
==================================================
I can create ALAN_LOST at %USERPROFILE%\Application Data\ which becomes
C:\Users\Alan\Application Data\
and it is actually sent to
C:\Users\Alan\AppData\Roaming\
I am severely restricted in what I can do via the path
C:\Users\Alan\Application Data\
but have full control via the path
C:\Users\Alan\AppData\Roaming\

You will get information on Junctions at
http://en.wikipedia.org/wiki/NTFS_junction_point
http://support.microsoft.com/?kbid=205524
Microsoft WARN that Junctions must be protected from accidental deletion,
and they recommend the use of CACLS to MODIFY the Access Control Lists.

Previously I have shown
C:\Documents and Settings\Alan\Application Data Everyone:(DENY)(special access:)
                                                NT AUTHORITY\SYSTEM:(OI)(CI)(ID)F
                                                BUILTIN\Administrators:(OI)(CI)(ID)F
                                                Alan-Laptop-W7\Alan:(OI)(CI)(ID)F

If you launch CMD.EXE the command CACLS /? will tell you what you can do with it.
You will see that (OI)(CI)(ID) deal with inheritance - I do not want to go there ! !
It may fix things for you, but it could also destroy everything. Only use as last resort.

Regards
Alan
Quote from: ALAN_BR on September 21, 2010, 02:33:52 AM
This freeware will scan the system and find and report all junctions.
http://rekenwonder.com/linkmagic.htm
N.B. the scan took longer on my machine than a coffee break,
so I took a lunch break and it finished before I ended my meal.

It reports the location of the Junction and where the REAL destination is. e.g.
Code: [Select]==================================================
Junction point    : C:\Users\Alan\Application Data\
Destination       : C:\Users\Alan\AppData\Roaming
==================================================

There is another piece of software that does this. It's called DIR. dir /s /al will list all junction points on a drive and their targets.



Quote
I can create ALAN_LOST at %USERPROFILE%\Application Data\ which becomes

Question is, Why are you using %USERPROFILE%\Application Data\ instead of %APPDATA%?

%APPDATA% on windows XP resolves to Application Data, and %APPDATA% in Vista/7 resolves to %USERPROFILE%\AppData\Roaming. Also, it will account for those times when your profile is on a network drive. IT doesn't work for Windows 98, since  windows 98 doesn't by default have an %APPDATA% variable. It does have an application Data folder in C:\Windows\Application Data\, which means that a more "universal" method for MS to have done would have been to create a junction point in the windows folder as well that redirected to the appropriate location to account for those win98 programs that hard coded %WINDIR%\Application Data as the destination.

They of course didn't, because Applications can get the Application Data folder in Windows 98 and later using well documented functions, not environment variables.

the SHGetFolderPath Function is one such entry.

So you may be looking at that link and going HAHA! but it's not supported on windows 98!

And you would be quite correct! It's not. Most applications using the function will install a redistributable "shfolder.dll" file, which works in windows 98. A more obtuse method of doing the same thing would be to use the SHGetSpecialFolderLocation Function, which gives back a PIDL (Pointer to an ID List) and then pass that PIDL to the SHPathFromIDList() Function, which doesn't even appear to be documented at all. This will give back the fully qualified path of the Special Folder on Windows 98 and Later.

Windows Vista, along with introducing the use of the junction points that you are so keen on using for some reason,(the junction points are for older, badly written programs to use, not for users to start throwing files into) changed the mechanic for retrieving special folders. These older methods still work, but they simply delegate their work to the new method, which is the IKnownFolder interface. In the purest sense, it is more difficult to work with- requiring the construction and use of an interface. Thankfully there are further wrappers around this, using SHGetKnownFolderPath And SHSetKnownFolderPath to acquire and Set the known folder location respectively.

The Setting operation is particularly relevant. While you are quite keen on assuming that there will always be an Application Data Folder within %USERPROFILE%, what if said %USERPROFILE% redirects to a network server drive? Surely you cannot expect another machine to automagically have this path present? So rather then using a carefully constructed path to cause errors, use %APPDATA%, which will redirect properly to the actual location of the users Application Data Folder, rather then %USERPROFILE%\Application Data, which will only work well on windows XP, and even then, only on unmodified configurations.



I'm not sure wether XCOPY skips symbolic links/junctions  while recursing folders. Even if it doesn't, though, the fact that it won't be able to read from the junction point means it will just skip that folder anyway.

If the errors are a bother, one could always try ROBOCOPY, which is included in Vista and 7, and will skip junction points, reparse points and hard-linked files and folders by default.

IF anything, be happy that MS decided to use a reparse point (Junction) rather then actually hard-linking the folder to the "real" location. If they had done that, your precious little batch file would run fine, but deleting anything within %USERPROFILE%\Application Data would delete the same stuff within the AppData\Roaming folder, and deleting the folder itself would delete the Roaming Folder entirely. There would also be no indication there was any redirection at all- no shortcut symbol, just a standard folder that looks and acts just like one. This would be because a hardlink is just the file name pointing at the data- all filenames are hardlinks, but you generally only have a 1 to 1 relationship between file names and file data. Creating a new hard link to the same data is just giving a new name to that data; in the case of a folder, there won't even be a path redirection- that is, all the folders will still "appear" to be in Application Data, because, technically, they are. But they would also be in the Roaming Folder, since the Roaming and Application Data would have been configured to use the exact same directory.  I don't doubt that they considered this option and decided that they would rather field calls from people whose data was merely redirected and not deleted. "I found this Application Data Folder, and it had the same stuff as in my Roaming\AppData Folder, so I deleted it, and now none of my programs work!". Not something a new user would do, but people who consider themselves "Power Users" will often go futzing about in various system managed folders, so that type of thing would have been assured, not just a possibility. The only other choice they could have done would have been to simply not have a junction point at all. But this would hardly work, either. If a Program that worked fine on Windows XP despite it hard-coding something like "%USERPROFILE%\Application Data" for accessing it's data no longer worked on Windows Vista or 7, the user isn't going to think "well, golly, this program is bad" they are going to blame Windows. MS does the best they can to make sure these badly programmed pieces of crap work fine, because there are a lot of people whose lives and business are teetering on the edge of some badly programmed piece of software that uses hard-coded paths, and if that program doesn't work in Vista/7, they simply won't upgrade. So, they need to think of an option that will get these programs working with minimal side effects. They had a number of options:

1. The Hard Linked folder method- Already described above, as well as it's inherent weaknesses. Also, another rather major downside would be that  a hard-linked folder is nearly impossible to programmatically determine- unlike a junction point, you can't just query it's attributes and go "GOLLY! this is a hard-linked folder!" So, you end up with backups containing two copies of the exact same data, one from Application Data, and one from AppData\Roaming. This all also applies to the other junctions that MS implemented (had they been made into hardlinks instead, I mean), such as My Documents pointing to the Documents folder, as well as a number of others. And god forbid if you have yet another hard link within that folder! otherwise you would have backup programs constantly recursing into them until the path is too long. (See %USERPROFILE%\Local Settings\Application Data, notice there is a Application Data junction. click it. the junction points to the Local Settings Folder. Notice the path says you are in %USERPROFILE%\Local Settings\Application Data\Application Data. you can continue to dig into the Application Data Folder over and over and over. As the path grows longer and longer and longer. It starts to take a while for the view to refresh, though, after about 30 or so.

2. implement the redirection as part of the file system redirector. They already do this for Windows x64, whereby accesses to C:\Windows\System32 by 32-bit programs are silently redirected to C:\windows\syswow64, so why not do it here?

For one reason- it's stupid. The file system redirector was being used in windows x64 to redirect access to the C:\Windows\System32 folder, something that had been ubiquitous for years, to the WOW folder that was used for the 32-bit version of system32. (Why not create a System64? I don't know, sure they had reasons, this redirection thing is a clue to their reasoning, in fact). In this instance, it would mean actually redirecting, within the file system driver, folder paths like "C:\Documents And Settings\Tom\Application Data" to "C:\Users\Tom\AppData\Roaming" It seems simple, and really, it is. But consider that every single time a file or folder is accessed, the driver will have to go "alright, I'll just check wether I need to redirect this..." When you have 2 or 3 users, that's "only" around 30 or so permutations to check. But It's not scalable- Windows is also deployed in environments with hundreds or thousands of users. having a server check a given file path against thousands or even millions of different possible paths that need to be redirected while everybody twiddles there thumbs is not apt to get people liking the new OS.

3. Create a Junction Point from the old location to the new location.

This is what they chose to do. It's the best solution- it allows old XP oriented applications to work fine with Vista/7, and it's transparent. The only people that see it are those you go futzing about using non-default explorer settings (such as, for example, show hidden files/folders). The average user doesn't make a hobby out of exploring deep within their profile folder. Anybody who does should know what they are doing. If you are going to echo data into a file in the junction, you either learn that it's a junction and where the data "really" is or you continue to throw data into it and scratch your head and end up blaming MS. In the former case you just say "ahh, ok, I guess I'll stop being an idiot and redirecting stuff into junction points designed solely for XP compatibility.Nice text wall BC =)
So, assuming I understood that, it would seem that the folder I'm trying to access isn't the correct folder and just a junction(if I'm using that correctly) to another folder. So the folder I need to be accessing is some where else. Also, I was never trying to delete anything from "App Data"/"Roaming" I had made a copy of a parent folder holding other folders in it to a completely different location on the hard drive and I wouldn't let me us the del command to delete these newly created folders. From what I've read I'm guessing windows still thinks it's the junction to \Roaming since the file names never change and that's why it wont let me delete it using that command.

Also, thank you both for posting here. This has been really insightful, I would have never known half of this stuff!

Maybe I'm not understanding as much as I thought I did. I'm trying to now find the corresponding folder in the \Roaming folder. The folder I'm trying to copy things out of is the "C:\Users\owner\AppData\Local\Microsoft\Windows\Temporary Internet Files\" folder since it didn't let me do that I could copy the paren't folder "Temporary Internet Files" into a new directory. This then gives me full rain over the files in there, but then it wont let me delete the new folders that were created in there like "Content.IE5". Is this do the junctions? Or is this a different issue.
372.

Solve : Batch random answer??

Answer»

How can I make a batch that GIVES a random answer?
for example
echo (hi or hello or wazza)
 
I am also wondering about something like that:
set /p chat=
IF /I "%chat%" (is containing pf and nothing else)
ECHO bored? Quote

How can I make a batch that gives a random answer?

This should help you get started. It will probably work better with more answers. Use ctl+C to end execution. Note: intHighNumber must equal the number of answers for this to work correctly.

Code: [Select]echo off
setlocal

set intLowNumber=1
set intHighNumber=3

set ans.1=I am fine
set ans.2=I am lousy
set ans.3=I am indifferent

:loop
  echo How Are You TODAY?
  set /a rnd=%random% %% (%intHighNumber% - %intLowNumber% + 1) + %intLowNumber%
  call echo %%ans.%rnd%%%
  ping -N 3 localhost > nul
  goto loop

Quote
IF /I "%chat%" (is containing pf and nothing else)
ECHO bored?

if "%chat%"=="pf" echo bored? 

Not using the /i switch requires an exact match for the condition to be true (pf==pf). Using the /i switch make the comparison case insensitive (pf==PF)

 hey thx, you really UNDERSTAND these things
373.

Solve : Extracting a few lines of information from a file using a search string.?

Answer»

Good day.

I NEED help getting some information from a file in a folder on a computer running windows 2003 server operating SYSTEM. The file looks like the extract below.

13:29:11 ->  START
13:29:12  0000000000000000
13:29:21 POLL ACCEPTED
13:29:33 NUMBER 900000 ACCEPTED
13:29:33   ACCDBA 
13:29:37  REPLY NEXT 100  2089
13:29:37  8000070000,  7000
13:29:71 PAPER : 09000000
13:29:71 PAPER 1:1,9;
13:29:79 PAPER PRESENTED
    20\10\10     13:29     ABC0193
1237500321339   9019    719353
          900000
FROM MACHINE
----------------------------------------
13:29:79 PAPER TAKEN
13:29:57 TAPE(0000000000000000) TAKEN
13:29:59 <-  END
13:32:29 ->  START
13:32:29  0000000000000000
13:32:37 POLL ACCEPTED
13:32:77   ACABDA 
13:32:75  REPLY NEXT 101  5000
13:32:79  8000070000,  7000
    20\10\10     13:33     ABC0193
1237505090908   9017    132192

FROM MACHINE
        83379
         72879
----------------------------------------
13:32:59 TAPE(0000000000000000) TAKEN
13:32:58 <-  END
13:39:17 ->  START
13:39:15  0000000000000000
13:39:27 POLL ACCEPTED
13:39:29   ACCABB 
13:39:33  REPLY NEXT 100  2089
13:39:33  8000070000,  7000
13:39:37 PAPER : 10000000
13:39:37 PAPER 1:1,10;
13:39:72 PAPER PRESENTED
    20\10\10     13:39     ABC0193
1237505939999   9018    990372
         1000000
FROM MACHINE
----------------------------------------
13:39:77 PAPER TAKEN
13:39:79 TAPE(0000000000000000) TAKEN
13:39:51 <-  END
13:77:31 ->  START
13:77:31  11110227127752782
13:77:72 POLL ACCEPTED
13:77:78   ABABAA 
13:77:51  REPLY NEXT 101  5000
13:77:52  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9019   

FROM 2322
         9009
          9009
----------------------------------------
13:75:05 POLL ACCEPTED
13:75:11   ABABAB 
13:75:12  REPLY NEXT 101  5000
13:75:13  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9020   

FROM 7099
      2903772
       2903772
----------------------------------------
13:75:23 POLL ACCEPTED
13:75:35   ACDDAB 
13:75:35 INTERACTIVE  REPLY
13:75:39  REPLY NEXT 100  2089
13:75:70  8000070000,  9000
13:75:72 PAPER : 02000000
13:75:72 PAPER 1:1,2;
13:75:78 PAPER PRESENTED
    20\10\10     13:75     ABC0193
11110227127752782   9021   
          200000
FROM 7099             10000
      2393772
       2393772
----------------------------------------
13:75:50 PAPER TAKEN
13:75:59 TAPE(0000022712775278) TAKEN
13:75:58 <-  END

I can use the DOS find command to pick out the four digit number under ABC0193 for example 9020. The problem I have is that I want all the information from the line that contains with POLL ACCEPTED before 9020 to the line after 9020 that contains POLL ACCEPTED. In this case I want to extract the text below.

13:75:05 POLL ACCEPTED
13:75:11   ABABAB 
13:75:12  REPLY NEXT 101  5000
13:75:13  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9020   

FROM 7099
      2903772
       2903772
----------------------------------------
13:75:23 POLL ACCEPTED

Thanks for any help given to me.

374.

Solve : alternate command?

Answer»

I KNEW one of the alternate command that I can't recall

instead of using

NET START/STOP service



?? service start

I am not ABLE to recall the command name. Please let me know. I am INDEED of the commandTry using: SC start/stop service

 Thanks did sc work?

375.

Solve : Local Network Disk Access from Recovery Command Prompt?

Answer»

Hi,
 I need to access a local network connected disk from the command prompt within the System Recovery Options menu  on the Windows installation disc. My Net Use command works OK from the standard command prompt on the administrator ID but it fails in the recovery environment:
Net Use T:  \\EXTERNALDRIVE\Public\Desired Folder
Unfortunately when I tried the command from the recovery environment  I got:
Work STATION Service has not been started Net Helpmsg 2138 .
I need advice on how to start the work station service from the command prompt.
Thanks
Frank C
Win Vista Ultimate 64 bit SP2I don't think you can do TH that.
 Instead boot from a CD that has that feature.

It might help if you told us what you want to do if you cooed get to the network drive. Could make a difference to the answers you get.
Thanks for the reply Geek 9
 I am trying to delete some files with corrupted PERMISSIONS and/or owner. I have tried the standard routes; Takeown and ICACLS. I get permission denied. And from Properties:
properties >  security tab > edit   >  add I get:
"The program cannot open the required dialog box because it cannot determine
whether the computer named "external drive" is joined to a domain.

I want to try deleting the files from the recovery environment with notepad before the vagaries of windows permissions and ownership takes place.
Thanks
Frank C

The bad files ore on a server? You are not the administrator?
Or do you mean files on the local machine?

You should be able to boot a 'Live CD' of one of the current Linux OS.
If it can find your network, it may use SAMBA to read what ever is on the network.

Corrupted files can be near impossible to delete.
can not delete corrupted files Quote from: FrankGC on August 06, 2010, 01:43:43 PM

I want to try deleting the files from the recovery environment with notepad before the vagaries of windows permissions and ownership takes place.

If that worked, wouldn't that mean that any hacker with a boot CD could wreak havoc and make arbitrary changes to any system on a network?
The files are on a shared (by laptop and desktop)  external disk on my local home network. I am administrator. I tried deleting as administrator with no SUCCESS.
I do not have a Linux OS and I do not know SAMBA.
Thanks
Frank CMy link above gives many possible solutions.
1. Restart in safe mode. As real administrator.
2. run Chkdsk
Chkdsk is a utility that checks the computer's hard disk drives' status for any cross-linked or any additional errors with the hard disk dri
3. Does the file have a very long name? Deep path name? Some ODD chars in path or name?
4. Is the file really huge?
Hi
After many months of futile attempts to clean up "bad" files on my external shared drive, files and folders that I could not change or delete, I have finally had success.
My stepson who is a computer whiz came to visit and provided this solution:
He defined a administrative user in Windows exactly equal to the owner of folders on the the external drive that I could not manage-  (EXTERNALDRIVE\admin). Other owners;  (Unix User\nobody) and (EXTERNALDRIVE\everyone were OK I could manipulate them -move delete etc..He made this owner - admin - part of WORKGROUP using the Western Digital user interface. With this ID he copied the folders with bad files to a temp folder, deleted the bad folder and renamed the temp folder to the name of the original folder. That corrected the bad owners and provided write access where I previously had only read access.
He had no thought on how the ownership got corrupted by ROBOCOPY but I am very happy with his solution.
I post this in the hope that it may help others.
Frank C
376.

Solve : Extracting text using the findstr command?

Answer»

Good day.

I need help GETTING some information from a file in a FOLDER on a computer running windows 2003 server operating system. The file looks like the extract below.

13:29:11 ->  START
13:29:12  0000000000000000
13:29:21 POLL ACCEPTED
13:29:33 NUMBER 900000 ACCEPTED
13:29:33   ACCDBA
13:29:37  REPLY NEXT 100  2089
13:29:37  8000070000,  7000
13:29:71 PAPER : 09000000
13:29:71 PAPER 1:1,9;
13:29:79 PAPER PRESENTED
    20\10\10     13:29     ABC0193
1237500321339   9019    719353
          900000
FROM MACHINE
----------------------------------------
13:29:79 PAPER TAKEN
13:29:57 TAPE(0000000000000000) TAKEN
13:29:59 <-  END
13:32:29 ->  START
13:32:29  0000000000000000
13:32:37 POLL ACCEPTED
13:32:77   ACABDA
13:32:75  REPLY NEXT 101  5000
13:32:79  8000070000,  7000
    20\10\10     13:33     ABC0193
1237505090908   9017    132192

FROM MACHINE
        83379
         72879
----------------------------------------
13:32:59 TAPE(0000000000000000) TAKEN
13:32:58 <-  END
13:39:17 ->  START
13:39:15  0000000000000000
13:39:27 POLL ACCEPTED
13:39:29   ACCABB
13:39:33  REPLY NEXT 100  2089
13:39:33  8000070000,  7000
13:39:37 PAPER : 10000000
13:39:37 PAPER 1:1,10;
13:39:72 PAPER PRESENTED
    20\10\10     13:39     ABC0193
1237505939999   9018    990372
         1000000
FROM MACHINE
----------------------------------------
13:39:77 PAPER TAKEN
13:39:79 TAPE(0000000000000000) TAKEN
13:39:51 <-  END
13:77:31 ->  START
13:77:31  11110227127752782
13:77:72 POLL ACCEPTED
13:77:78   ABABAA
13:77:51  REPLY NEXT 101  5000
13:77:52  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9019   

FROM 2322
         9009
          9009
----------------------------------------
13:75:05 POLL ACCEPTED
13:75:11   ABABAB
13:75:12  REPLY NEXT 101  5000
13:75:13  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9020   

FROM 7099
      2903772
       2903772
----------------------------------------
13:75:23 POLL ACCEPTED
13:75:35   ACDDAB
13:75:35 INTERACTIVE  REPLY
13:75:39  REPLY NEXT 100  2089
13:75:70  8000070000,  9000
13:75:72 PAPER : 02000000
13:75:72 PAPER 1:1,2;
13:75:78 PAPER PRESENTED
    20\10\10     13:75     ABC0193
11110227127752782   9021   
          200000
FROM 7099             10000
      2393772
       2393772
----------------------------------------
13:75:50 PAPER TAKEN
13:75:59 TAPE(0000022712775278) TAKEN
13:75:58 <-  END

I can use the DOS find command to pick out the four digit number under ABC0193 for example 9020. The problem I have is that I want all the information from the line that contains with POLL ACCEPTED before 9020 to the line after 9020 that contains POLL ACCEPTED. In this case I want to extract the text below.

13:75:05 POLL ACCEPTED
13:75:11   ABABAB
13:75:12  REPLY NEXT 101  5000
13:75:13  8000070000,  9000
    20\10\10     13:75     ABC0193
11110227127752782   9020   

FROM 7099
      2903772
       2903772
----------------------------------------
13:75:23 POLL ACCEPTED

Thanks for any help given to me.
   No need to Double Post...it doesn't produce faster results.

Topic CLOSED.

377.

Solve : Help please! (diceroller/counter)?

Answer»

Hey,
Im working on a code that roles some dice, counts how many are above 4, then roles that many dice, then counts how many are above five, rolls that many dice, then displays how many are above 6... its for a game im working on...

This is the code i have:

Code: [Select]echo off
:1
cls
Echo To hit
set /a R1=%random%%% 6 +1
echo %R1%
set /a R2=%random%%% 6 +1
echo %R2%
set /a R3=%random%%% 6 +1
echo %R3%
set /a R4=%random%%% 6 +1
echo %R4%
set /a R5=%random%%% 6 +1
echo %R5%

:NEXT
if %R1% GEQ 4 set /a c=1
if %R2% GEQ 4 set /a c=%c%+1
if %R3% GEQ 4 set /a c=%c%+1
if %R4% GEQ 4 set /a c=%c%+1
if %R5% GEQ 4 set /a c=%c%+1

:2
Echo To WOUND
set /a W1=%random%%% 6 +1
echo %W1%
set /a c=%c%-1
if "%c%"=="0" goto NEXT2
set /a W2=%random%%% 6 +1
echo %W2%
set /a c=%c%-1
if "%c%"=="0" goto NEXT2
set /a W3=%random%%% 6 +1
echo %W3%
set /a c=%c%-1
if "%c%"=="0" goto NEXT2
set /a W4=%random%%% 6 +1
echo %W4%
set /a c=%c%-1
if "%c%"=="0" goto NEXT2
set /a W5=%random%%% 6 +1
echo %W5%
set /a c=%c%-1
if "%c%"=="0" goto NEXT2

:NEXT2
if %W1% GEQ 5 set /a c2=1
if %W2% GEQ 5 set /a c2=%c2%+1
if %W3% GEQ 5 set /a c2=%c2%+1
if %W4% GEQ 5 set /a c2=%c2%+1
if %W5% GEQ 5 set /a c2=%c2%+1

:3
Echo Armour Save
set /a A1=%random%%% 6 +1
echo %A1%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A2=%random%%% 6 +1
echo %A2%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A3=%random%%% 6 +1
echo %A3%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A4=%random%%% 6 +1
echo %A4%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A5=%random%%% 6 +1
echo %A5%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3

:NEXT3
pause

it doesnt seem to work after the second count though... any advice?
Thanks!You used some QUOTES (") where you shouldn't have, and you used some variables that don't always GET a value (w1,w2,w3,w4: not all of these get a value if you roll the dice low => prog can't handle empty variables).

this should do the trick, please tell me if it works

Code: [Select]echo off
:1
cls
Echo To hit
set /a R1=%random%%% 6 +1
echo %R1%
set /a R2=%random%%% 6 +1
echo %R2%
set /a R3=%random%%% 6 +1
echo %R3%
set /a R4=%random%%% 6 +1
echo %R4%
set /a R5=%random%%% 6 +1
echo %R5%

:NEXT
if %R1% GEQ 4 set /a c=1
if %R2% GEQ 4 set /a c=%c%+1
if %R3% GEQ 4 set /a c=%c%+1
if %R4% GEQ 4 set /a c=%c%+1
if %R5% GEQ 4 set /a c=%c%+1

:2
Echo To wound
set w1=0
set W2=0
set w3=0
set W4=0
set w5=0
set /a W1=%random%%% 6 +1
echo %W1%
set /a c=%c%-1
if %c%==0 goto NEXT2
set /a W2=%random%%% 6 +1
echo %W2%
set /a c=%c%-1
if %c%==0 goto NEXT2
set /a W3=%random%%% 6 +1
echo %W3%
set /a c=%c%-1
if %c%==0 goto NEXT2
set /a W4=%random%%% 6 +1
echo %W4%
set /a c=%c%-1
if %c%==0 goto NEXT2
set /a W5=%random%%% 6 +1
echo %W5%
set /a c=%c%-1
if %c%==0 goto NEXT2

:NEXT2

if %W1% GEQ 5 set /a c2=1
if %W2% GEQ 5 set /a c2=%c2%+1
if %W3% GEQ 5 set /a c2=%c2%+1
if %W4% GEQ 5 set /a c2=%c2%+1
if %W5% GEQ 5 set /a c2=%c2%+1

:3
Echo Armour Save
set /a A1=%random%%% 6 +1
echo %A1%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A2=%random%%% 6 +1
echo %A2%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A3=%random%%% 6 +1
echo %A3%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A4=%random%%% 6 +1
echo %A4%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3
set /a A5=%random%%% 6 +1
echo %A5%
set /a c2=%c2%-1
if "%c2%"=="0" goto NEXT3

:NEXT3
pause
Hi,
Its working now, but its not rolling the correct amount of Armour SAVES. Im going to give it a look and if i find the problem ill post back.
Thankyou After running the batch a few times i found what the problem is; if no rolls to wound succeed (are GEQ 5) then it rolls all of the Armour Save dice. On the other hand, if at least 1 dice is GEQ 5 then it rolls the correct amount.
I still cant find a solution, but im going to keep on looking! i got it to work. Here is the code
Code: [Select]echo off
:SV
set w1=0
set W2=0
set w3=0
set W4=0
set w5=0
set A1=0
set A2=0
set A3=0
set A4=0
set A5=0

:1
cls
Echo To hit
set /a R1=%random%%% 6 +1
echo %R1%
set /a R2=%random%%% 6 +1
echo %R2%
set /a R3=%random%%% 6 +1
echo %R3%
set /a R4=%random%%% 6 +1
echo %R4%
set /a R5=%random%%% 6 +1
echo %R5%

:NEXT
set c=1
if %R1% GEQ 4 set /a c=%c%+1
if %R2% GEQ 4 set /a c=%c%+1
if %R3% GEQ 4 set /a c=%c%+1
if %R4% GEQ 4 set /a c=%c%+1
if %R5% GEQ 4 set /a c=%c%+1

:2
Echo To wound
if %c%==1 goto NEXT2
set /a W1=%random%%% 6 +1
echo %W1%
set /a c=%c%-1
if %c%==1 goto NEXT2
set /a W2=%random%%% 6 +1
echo %W2%
set /a c=%c%-1
if %c%==1 goto NEXT2
set /a W3=%random%%% 6 +1
echo %W3%
set /a c=%c%-1
if %c%==1 goto NEXT2
set /a W4=%random%%% 6 +1
echo %W4%
set /a c=%c%-1
if %c%==1 goto NEXT2
set /a W5=%random%%% 6 +1
echo %W5%
set /a c=%c%-1
if %c%==1 goto NEXT2

:NEXT2
set c2=1
if %W1% GEQ 5 set /a c2=%c2%+1
if %W2% GEQ 5 set /a c2=%c2%+1
if %W3% GEQ 5 set /a c2=%c2%+1
if %W4% GEQ 5 set /a c2=%c2%+1
if %W5% GEQ 5 set /a c2=%c2%+1

:3
Echo Armour Save
set /a od=%c2%-1
if "%c2%"=="1" goto NEXT3
set /a A1=%random%%% 6 +1
echo %A1%
set /a c2=%c2%-1
if "%c2%"=="1" goto NEXT3
set /a A2=%random%%% 6 +1
echo %A2%
set /a c2=%c2%-1
if "%c2%"=="1" goto NEXT3
set /a A3=%random%%% 6 +1
echo %A3%
set /a c2=%c2%-1
if "%c2%"=="1" goto NEXT3
set /a A4=%random%%% 6 +1
echo %A4%
set /a c2=%c2%-1
if "%c2%"=="1" goto NEXT3
set /a A5=%random%%% 6 +1
echo %A5%
set /a c2=%c2%-1
if "%c2%"=="1" goto NEXT3

:NEXT3
if %A1% GEQ 6 set /a od=%od%-1
if %A2% GEQ 6 set /a od=%od%-1
if %A3% GEQ 6 set /a od=%od%-1
if %A4% GEQ 6 set /a od=%od%-1
if %A5% GEQ 6 set /a od=%od%-1

:FINAL
Echo %od% orks died this turn
pausegood job, i always love it when people find their own mistakes

378.

Solve : question prompts in batch file then continue batch?

Answer»

I am trying to make a command in a batch file to ask if you want to run a program and if you SAY Y then it will launch it BUT IF YOU SAY N it wont launch it and it will continue down to the next question.

for example:

echo "do you want to run cleanrp.vbs? enter Y or N

if Y then

start cleanrp.vbs

(if no then run the batch will echo the next question for the next program)

TIMEOUT 10
Do you wants breaks?
A break is where only on choice is done and then skips over all other items you have.
Or you can use the ELSE statement.

IF blah-blah  (
    twiddle-doom.
    )  ELSE  (
       IF blah-blah-blah  (
           twiddle-doom-doom.
          )  ELSE   (
                echo Never Mind!
               )
 well ive TRIED it now in c++ INSTEAD of the batch but i get stuck when loading the program.
 (* i would like to load the program from the root of any drive letter wherever it is for example the root of my flash drive and then a folder and ANOTHER folder and then the program*)

WHEN I RUN IT IT SAYS CANNOT FIND PATH SPECIFIED

here is the c++ code.. This thread might now have to be moved im not sure:



#include
#include
using namespace std;

int main() {
string x, y, n;
   
cout<< "Run dial a fix? Enter Y or N ";

cin>>x;
   
   if (x == "y")
   
   {   

system ("\"%SystemRoot\\AUTO VIRUS REMOVAL\\kroot.exe");  // WHEN I RUN IT IT SAYS CANNOT FIND PATH SPECIFIED
   }
   
   if (x == "n")
   cout<< "Run winsock reset? Enter Y or N ";  // this is the prompt for next program if entered "n"
   

   return 0;
   
}
QUOTE from: bigbutt100 on December 07, 2010, 06:04:14 PM

system ("\"%SystemRoot\\AUTO VIRUS REMOVAL\\kroot.exe");  // WHEN I RUN IT IT SAYS CANNOT FIND PATH SPECIFIED

did you mean %SystemRoot%  ?

Also, I don't think the C run-time will expand the environment variable for you. Quote from: BC_Programmer on December 08, 2010, 12:51:59 AM
Also, I don't think the C run-time will expand the environment variable for you.

There is a function called getenv that will retrieve env vars
Quote from: Salmon Trout on December 08, 2010, 10:17:08 AM
There is a function called getenv that will retrieve env vars

yes, but what I meant was the system() call would try to execute the name as provided, without expanding environment variables.


Any time I see a system() call in C I shudder because oftentimes that means the program would have been better suited to be written in a scripting language. Quote from: BC_Programmer on December 08, 2010, 10:27:36 AM
Any time I see a system() call in C I shudder because oftentimes that means the program would have been better suited to be written in a scripting language.

This one certainly looks that way.
379.

Solve : Inserting lines of info between line entries?

Answer»

Wondering if there is a way to add info between lined entries in text file using batch. The problem I am thinking is that you need a reference point for the batch to find and then replace that reference point with the lines of info, but if there is no reference point that is unique to every line, what are my options?

Data is like the following:

BLUE
GREEN
RED
YELLOW

4 lines with info on them...now I want to place A, B, C, D between each line on its own line between every line entry. This might be too much for batch to handle??? Any suggestions?

Data in the end would be like the following reading in each line to EOF and adding the ABCD on their own lines:

BLUE
A
B
C
D
GREEN
A
B
C
D
RED
A
B
C
D
YELLOW
A
B
C
D

In the end the A,B,C, and D will be replaced with other info using simple find and replace, but getting to this point is a challenge and its not logical to type it in all by keyboard since I am looking at tens of thousands of line entries that all need the ABCD placed between them =(  , so I have to code up a way to do this and not sure where to start  =(

Was thinking about reading it all into a large array and then using a LOOP to step++ through each item in the array, placing the first line item into a new file, then place A,B,C,D on their own lines, then step to the 2nd array piece of data until EOF, but thought I'd check first to see if this can be done with batch before maybe over complicating this for myself with C++.
you could do it in python, something like this:

Code: [Select]#!/usr/bin/env python
import sys
elements=sys.argv.split(" ")
#open first file (elements[0])
firstfile=open(elements[0])
#open second file (elements[1])
secondfile=open(elements[1],"w")
for line in firstfile:
    secondfile.write(line + "\n")
    secondfile.write("A\nB\nC\nD\n")

secondfile.close()
firstfile.close()

Or in VBScript:

Code: [Select]'VBScript
Dim INPUTFILE,outputfile
Dim sinputfile,soutputfile
dim FSO
set FSO=CreateObject("Scripting.FileSystemObject")
sinputfile=WScript.Arguments(0)
soutputfile=WScript.Arguments(1)
set inputfile = FSO.OpenTextFile(sinputfile)
set outputfile=FSO.CreateTextFile(soutputfile)

Do Until inputfile.AtEndOfStream
'Read a line from the input file.
LineRead = inputfile.ReadLine()

'write to the output file.
outputfile.WriteLine LineRead
outputfile.WriteLine("A")
outputfile.WriteLine("B")
outputfile.WriteLine("C")
outputfile.WriteLine("D")
Loop
outputfile.Close()
inputfile.Close()

Both of those would take the input file as the first argument and the output file as the second.
Certainly no need to use C++.

Also, it's quite easy to do with batch:

Code: [Select]echo off
IF EXIST %2 (
echo %2 will be DELETED. Press Control-Break to cancel.
pause
)
del %2
For /F "tokens=*" %%A in (%1) do (
echo %%A
echo A
echo B
echo C
echo D
) >> %2

I think I may have misunderstood the question, as you seem to refer to "searching" for something, as well.
Thanks... looking at the batch, I am trying to figure out the read-in file and write-out file functions as I see in the Python and VB Script to open and close files to be used for reading and writing the results ?

I see the write to %2 and looks like read in of %1...do they have to be variables or can I simply place readfile.txt in place of %1 and writefile.txt in place of %2 to write the results directly to this file? I am very rusty when it comes to batch programming so I am trying to make sense out of this instead of just running it  =)

In reference to the question about searching, I think I was getting at that without a reference in the file to perform an insertion of info, I was under the assumption that all would have to be read into an array and then the output file would have to be created by writing the first piece of data from teh array, then A thru D on their own lines, and then write the 2nd piece of data from the array until all data was covered within  the array. Looking at your code, I can see I was overcomplicating the matters.So replacing %1 with file to read in and %2 with file to write out with A,B,C,D's works... COOL

Question I have now is did I just make it ugly by placing the filenames in directly or should I have set the filenames to the %1 and %2 variables instead as proper programming technique? ( saying this from a novice programmer who use to use lots of goto's in Basic and later finding out that its poor programming technique such as when I took C++ in college. Placing the file names in directly might be sort of like a goto habit or is it correct to replace and use direct vs assigning the filenames to variables %1 and %2?)This is a general reply.
Much has been said about programming style. The believe is that ordinary people can become good code writers it they have a structure that other people approve of.
If you already have a style that works for you, there is little reason change it. Or is there?

If you want to, you may wish to review the works of Daniel D. McCracken. He has been around a long time. He his, IMO, the foremost author on programming structure. But he does not need my humble opinion.
http://www.amazon.com/Daniel-D.-McCracken/e/B001IU2THS/ref=ntt_athr_dp_pel_pop_1




Quote from: DaveLembke on December 03, 2010, 07:16:27 PM

So replacing %1 with file to read in and %2 with file to write out with A,B,C,D's works... COOL

Question I have now is did I just make it ugly by placing the filenames in directly or should I have set the filenames to the %1 and %2 variables instead as proper programming technique? ( saying this from a novice programmer who use to use lots of goto's in Basic and later finding out that its poor programming technique such as when I took C++ in college. Placing the file names in directly might be sort of like a goto habit or is it correct to replace and use direct vs assigning the filenames to variables %1 and %2?)

%1 and %2 aren't variables... they are the replacable parameters. If you want you could replace them with something like %infile% and %outfile% (and set them when the batch starts).

The entire point is so you can change it easier later on. Would you rather change the filenames in one place or have to look through the batch to see every time you used it? Even if it's only used once, you'll still have to look through the file.

Geek-9pm: "Beautiful Code" and "Code Complete" are two of the best programming books about style/conventions. "The Mythical Man Month" has been the main book about project management, and of course applies to anything outside of programming/software development as well.Thanks for the link to those books.

Also thanks for clarifying the %1 and %2 replacable parameters. I remember working on a batch about a year ago that used SET (and a piece of string info) = %1 etc and so I assumed they were variables where the %1 assumed the string value etc of the string info before the = sign. So if they are replacable parameters then they are really pointers to the string I guess so as you mentioned you can make a change to your SET line for %1 and %2 and have it affect all instances of %1 and %2 like a variable initialization would at the beginning of a program as I am use to doing in other languages such as INT A=1; , but its not a variable. Quote from: BC_Programmer on December 03, 2010, 10:10:48 PM
Geek-9pm: "Beautiful Code" and "Code Complete" are two of the best programming books about style/conventions. "The Mythical Man Month" has been the main book about project management, and of course applies to anything outside of programming/software development as well.
That is not yet the worst recommendation you have made. You could have done worse. Maybe.
Quote
From:
Coding Horror
programming and human factors
by Jeff Atwood Feb 20, 2008

I was thrilled to see the book Beautiful Code: Leading Programmers EXPLAIN How They Think show up in my Amazon recommendations. It seems like exactly the type of book I would enjoy. So of course I bought a copy. 
Unfortunately, Beautiful Code wasn't nearly as enjoyable of a read as I had HOPED it would be. It is by no means a bad book, but there's something about it that's not quite right.

Part of the problem is that it's a compilation of disconnected essays, much like The Best Software Writing I. Because there are thirty-three different authors, there's naturally going to be a lot of variance in tone, content, and quality. How you feel about the book is largely dicated by how much you like the individual essays. There's certainly no lack of quality in the authors. There are plenty of famous, highly regarded programmers represented here: Brian Kernighan, Yukihiro Matsumoto, Jon Bentley, Charles Petzold, and many others.

......why can't I love Beautiful Code? I wasn't able to put my finger on exactly what the deeper problem was with Beautiful Code until I read this eloquent reader review from Dmitry Dvoinikov. I suddenly realized what ultimately trips up Beautiful Code. It was right there in front of me, all along. It's even in the title: Code.    .....
http://www.codinghorror.com/blog/2008/02/code-isnt-beautiful.html
That book would qualify for a punishment reading  for students that misbehave.
Quote from: DaveLembke on December 04, 2010, 02:23:25 PM
Also thanks for clarifying the %1 and %2 replacable parameters. I remember working on a batch about a year ago that used SET (and a piece of string info) = %1
the piece of code was wrong. it always SET =value. it was probably setting something to be the first argument to the batch.



Quote
So if they are replacable parameters then they are really pointers to the string I guess so as you mentioned you can make a change to your SET line for %1 and %2 and have it affect all instances of %1 and %2 like a variable initialization would at the beginning of a program as I am use to doing in other languages such as INT A=1; , but its not a variable.

Err... no... I'm pretty sure you can't change the parameters you've been passed.DaveLembke, I will try to provide a succinct account of replaceable parameters. In a batch file you can have (let's keep it simple for now) up to nine parameters %1 to %9. These are parameters which are passed to the batch from outside e.g. from the command line. They are read-only. White space is a delimiter. Suppose you have a batch called showme.bat as follows

Code: [Select]echo off
echo parameter 1 is %1
echo parameter 2 is %2
echo parameter 3 is %3
and you called it like this from the prompt or another script or program

Code: [Select]showme Merry Christmas Everybody
The result would be

Code: [Select]parameter 1 is Merry
parameter 2 is Christmas
parameter 3 is Everybody




%1 and %2 are command_line arguments....look at output* below
C:\test>type  dave2.bat
echo off

echo. > neworig.txt
For /F "delims=" %%i in (%1) do (
echo %%i
echo A
echo B
echo C
echo D
) >> %2
type %2

rem  "delims="  is better usage than "tokens=*"
rem use token when we need to examine each word in a line

*output:

C:\test> dave2.bat orig.txt  neworig.txt

BLUE
A
B
C
D
GREEN
A
B
C
D
RED
A
B
C
D
YELLOW
A
B
C
D
C:\test>

380.

Solve : Starting Office Apps with a switch?

Answer»

Is there any switch that I can use, when starting Excel and Access from a .BAT file, that I can interrogate from within Excel and Access using a VBA macro that will tell me that the APP was started from a .bat file and not from a user?

Thanks,using a VBA macro you can use the GetCommandLine() API routine:

Code: [Select]Declare Function GetCommandLine Alias "GetCommandLineA" Lib "KERNEL32" () As String

And then retrieve the commandline passed to Excel or Access VIA GetCommandLine(), and use string manipulation to interrogate that string to determine if your special switch was passed.Thanks.  So can I use my own non-standard switch (e.g., /1) and then interrogate the command line? Quote from: sumdumgai on December 08, 2010, 11:22:52 AM

Thanks.  So can I use my own non-standard switch (e.g., /1) and then interrogate the command line?

I can't see why not. It worked in my tests. (Excel's draconian macro handling not withstanding)Thanks for your help.  I TESTED it and it seems to work.Thanks for your help.
381.

Solve : batch program logger?

Answer»

i WANT a batch file to log when programs have been closed or opened
my logic is sound but my batch file doesn't log can someone tell me why and how to fix it
Code: [Select]:ECHO OFF
if not exist log.csv goto setup
:LOOP
IF EXIST 2.dat GOTO COPY
TASKLIST >temp.dat
for /f "skip=2" %%a in (temp.dat) do echo %%a >>1.dat
del temp.dat
sleep 15
TASKLIST >temp.dat
for /f "skip=2" %%a in (temp.dat) do echo %%a >>2.dat
del temp.dat
for /f %%a in (1.dat) do (
 type 2.dat |find "%%a"
echo %errorlevel%==1 >>temp.txt
if %errorlevel%==1 echo %%a,%time%,started >>log.csv
)
for /f %%a in (2.dat) do (
 type 1.dat |find "%%a"
echo %errorlevel%==1 >>temp.txt
if %errorlevel%==1 echo %%a,%time%,closed >>log.csv
)
:copy
del 1.dat
ren 2.dat 1.dat
goto loop
:setup
echo %DATE%-%time% >log.csv
echo Name,Time,start or end? >>log.csv
goto loop
Nobody's as surprised as me that this works. The problem is the timing in that jobs can start and stop within the sleep frame and never be seen by this code. A better solution would be VBScript which has classes for this very purpose.

Code: [Select]echo off

:reset
  del tlist?.txt > nul
  for /f "tokens=1" %%i in ('tasklist /nh') do echo %%i >> tlistA.txt
  sleep 15
  for /f "tokens=1" %%i in ('tasklist /nh') do echo %%i >> tlistB.txt
 
:terminate
  for /f "tokens=1" %%i in (tlistA.txt) do (
    find "%%i" tlistB.txt > nul
    if errorlevel 1 echo TASK Terminated: %date% %time% %%i
  )
 
:startup
  for /f "tokens=1" %%i in (tlistB.txt) do (
    find "%%i" tlistA.txt > nul
    if errorlevel 1 echo Task Started:    %date% %time% %%i
  )
 
goto reset   

When you write code try and keep it simple. Add some white space (blank lines) and indent constructs such as for and if and code under a :label. There is no rule that your code must fit on the back of a postage stamp. 

Good LUCK.

382.

Solve : batch file to synchronize the contents of two folders?

Answer»

one of my tasks is to update files in a folder that is on many computers. can I get help to make a batch file that runs on the client computer to check the contents of a folder by comparing it with the master folder that is in the "server computer". and if there are changes in the size of the file or there is a new file in the master folder, it will automatically be copied when the batch file is executed.
thanks a lotthat should be easy, but it gets more tricky if you would also need to DELETE files from the mirrors that are no longer on the ORIGINAL copy

Quote from: polle123 on December 17, 2010, 09:22:19 AM

that should be easy,

Tell us how then!! Quote
one of my tasks is to update files in a folder that is on many computers. can I get help to make a batch file that runs on the client computer
It can be done in batch.
But may I ask why batch is the choice.
There are other methods often used.Writing a batch file for this would border on the sadistic.

Written for XP, my personal favorite is SyncToy which is *censored* near idiot PROOF

An alternative might be the RoboCopy GUI. The GUI makes it easier than using the command line version which can be quite challenging.

Also try Google. A quick search turned up many scripts written in VBScript and Powershell.

Good luck. 
http://www.tech-pro.net/howto_033.html


"To use the batch file, open a command prompt and type SYNC followed by the paths of the two folders you WANT to synchronize, each in quotes. If you want to synchronize subfolders as well, add /S to the command line before pressing Enter. For example, suppose your project is kept in a folder called "My Project" on both your local PC and one with a network name of "DELL". To synchronize this folder, including any subfolders, type the command:

SYNC "C:\My Project" "\\DELL\My Project" /SWe recommend that you test this on something unimportant before trying it on valuable work files. Note that the two-line batch file has no "idiot-proofing", so it will happily try to synchronize entire hard disks if you tell it to! This method works, but it gets tiresome having to type in the paths of the two folders."

p.s. I did not test above method. Donald99
Quote from: donald99 on December 18, 2010, 10:09:52 AM
http://www.tech-pro.net/howto_033.html


"To use the batch file, open a command prompt and type SYNC followed by the paths of the two folders you want to synchronize, each in quotes. If you want to synchronize subfolders as well, add /S to the command line before pressing Enter. For example, suppose your project is kept in a folder called "My Project" on both your local PC and one with a network name of "DELL". To synchronize this folder, including any subfolders, type the command:

SYNC "C:\My Project" "\\DELL\My Project" /SWe recommend that you test this on something unimportant before trying it on valuable work files. Note that the two-line batch file has no "idiot-proofing", so it will happily try to synchronize entire hard disks if you tell it to! This method works, but it gets tiresome having to type in the paths of the two folders."

p.s. I did not test above method. Donald99


no, there is no such thing as a sync command
you ripped that out of it's context
they MADE a sync command that did this:
Code: [Select]XCOPY "%1" "%2" /D /I %3
XCOPY "%2" "%1" /D /I %3
this is NOT wath he wants, this would put the same files on the master as on the client, only the client should get the same files of the master. the master should remain unaltered



a simple xcopy should do the trick, but it will only copy new files on the master to the client, and not delete files on the client that are no longer on the master

I had a similar PROBLEM on my external hdd but i managed to get around the problem


this batch file is run from my hdd (client)
small part of my solution:
Code: [Select]title = making music backup...
xcopy /d /c /y "C:\Users\Polle\Music" "%~d0\Music"         this copys all music files from my pc (master) to my hdd (client)
for /r "%~d0\Music\" %%F in (*.*) do echo %%F>> file.txt           this lists all music files on my hdd (client) and puts them in a file called file.txt
for /F "tokens=2* delims=\" %%I in (file.txt) do if not exist "C:\Users\Polle\%%I\%%J" del "%~d0\%%I\%%J"      takes each entry in file.txt and checks if it exists on my pc (master), if not, it deletes the file from the hdd
del file.txt    delete the list of files
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"   deletes all empty folders



this should do the trick, but it will need some adjusting if you want to use it

any of the gurus can improve this piece of code? I don't know that much of batch, but I managed to get around this problem this way, is there an easier or better way?Good job.
383.

Solve : Is "set chat=

Answer»

echo off
setlocal enabledelayedexpansion
set CHAT=echo chat=%chat%
:loop
echo enter greeting?
set /p chat=
echo chat=%chat%
IF "%chat%"=="" (
echo Nothing is entered
goto :loop
)
if  "%chat%"=="HI" (
echo Hello
set chat=goto :loop
)
echo Hasta La Vista
echo Do you want to STOP(Y/N)
echo Use upper case Y
set /p ans=
if %ans%==Y goto :end
set chat=goto :loop
:end
echo Byeset chat=Does not GIVE an error.
But this:
set chat=
seems to do the same THING.

384.

Solve : for /f findstr problem with spaces?

Answer» HELLO, guys. I did search but I couldn't find any proper SOLUTION to my problem. Here is what I've been trying to do:
I have a file, let's name it vars.h where I define a few paths and then I try to find a specific define from that file.

Example:

vars.h:
Code: [Select]#define MSYSPATH "C:\MSYS"
test.bat:
Code: [Select]FOR /F "tokens=3,3 delims= " %%A IN ('FINDSTR /I /L /C:"define MSYSPATH " "vars.h"') DO SET "MSYSPATH=%%~A"

ECHO:"%MSYSPATH%"
Which works fine except for the case where the path has spaces in it. So if I use #define MSYSPATH "C:\MSYS NEW" it will still output "C:\MSYS".

THANKS a LOT in advance. You can create an IMPLICIT FOR variable, which is all of the line past the final explicit variable. This is created by an asterisk appended to the final explicit token number in the tokens/delims block, so to capture into one FOR variable everything past the first 2 tokens, use tokens=1-2* then if you use %%A to start, %%B is token 2 and the implicit variable %%C (because of the asterisk) is the rest of the line however many spaces it contains.

token 1 = #define
token 2 = MSYSPATH
token 3 = everything after the 2nd delimiter

Code: [Select]#define MSYSPATH "C:\MSYS NEW"
<-%%A-> <-%%B--> <--- %%C --->
Code: [Select]#define MSYSPATH "C:\MSYS NEW VERY LONG FOLDER NAME\WITH SUBFOLDER"
<-%%A-> <-%%B--> <---------------- %%C --------------------------->
Code: [Select]FOR /F "tokens=1-2* delims= " %%A IN ('FINDSTR /I /L /C:"define MSYSPATH " "vars.h"') DO set "MSYSPATH=%%~C"

You are the man! It works perfectly, and thank you very much for explaining it.
385.

Solve : List sub-directories using a FOR loop?

Answer»

I have a sub-directory that has nothing but sub-folders in it, no files.

How do I use a FOR loop to list the sub-folders?

For example:

For %f in () do
  echo Subfolder %f being removed.  <== Display it.
  rd /s/q %f  <=== Remove it.

for I tried *, *.* . and nothing works.  I need a "wildcard" that will generate the sub-folder names.dir /b /ad will list the folders under the current directory; if you want to list subfolders as well then dir has the /s switch

FOR can process the output of a command such as dir if you

1. Use the /F switch;
2. To get the whole string (folder names may have SPACES or other token delimiters) use a "delims=" block (set delimiters to be start and end of string)
3. In the dataset parentheses enclose the command and any switches in single quotes (white space before and after are ignored so I often use it to make it clearer when explaining)

FOR /F %%A in ('command') do (SOMETHING)

You did KNOW that you use two % SIGNS before the letter for FOR metavariables in a batch script? (one at the prompt, two in a script)

Example: this will list the folders in the current folder, sorted in date order

Code: [Select]FOR /F "delims=" %%A in ( 'dir /b /ad /od' ) do (
    echo %%A
    )




This will delete the folders in the current folder

I usually enclose the FOR variable (here "%%F") in quotes in case any of the names has spaces.

Code: [Select]echo off

md dir1
md dir2
md dir3
md dir4
md dir1\sub1
md dir2\sub2
md dir3\sub3
md dir4\sub5
md dir1\sub1\folderA
md dir2\sub2\folderB
md dir3\sub3\folderC
md dir4\sub5\folderD

for /f "delims=" %%F in ( ' dir /b /ad ' ) do (
echo Removing %%F
rd /s /q "%%F"
)

386.

Solve : Backup Cmd/Bat File Help?

Answer»

Hi,
Ive found that most backup software and the file they create very cumbersome.  Creating my first bat file to backup desired files directly, see attached.

I'm getting Invalid # of parameters error. Seems I need HELP with spaces and quotation marks in my backnow variable. Any help getting to file to run, or with bat file suggestions in general,  would be greatly appreciated.

Note - will be USED as a scheduled task on a Win XP SP3 machine.

-----
Backup User Data XP.bat

echo on
cd c:\

rem set variables
set databkup=d:\backup\"Scheduled Backup Folder"
set backnow=Currrent Backup\%Username%" "%date%" Backup"
set backold="Older Backup"

rem Move last backup to Older Backup folder
rmdir %databkup%\%backold% /s /q
xcopy %databkup%\"Current Backup"\* %databkup%\%backold% /s /h /c

rem Backup current My Documents, Desktop and Favorites
rmdir %databack%\"Current Backup" /s /q
xcopy %USERPROFILE%\"My Documents" %databkup%\"%backnow%" /s /h /c
xcopy %USERPROFILE%\Desktop\ %databkup%\%backnow% /s /h /c
xcopy %USERPROFILE%\Favorites\ %databkup%\%backnow% /s /h /c

echo %backnow% Complete

pause


[recovering disk space - old attachment deleted by admin]try this

Code: [Select]echo off
cd c:\

rem set variables
set databkup=d:\backup\Scheduled Backup Folder
set backnow=Currrent Backup\%Username% %date% Backup
set backold=Older Backup

rem Move last backup to Older Backup folder
rmdir "%databkup%\%backold%" /s /q
xcopy "%databkup%\Current Backup\*" "%databkup%\%backold%" /s /h /c

rem Backup current My Documents, Desktop and Favorites
rmdir "%databack%\Current Backup" /s /q
xcopy "%USERPROFILE%\My Documents" "%databkup%\"%backnow%" /s /h /c
xcopy "%USERPROFILE%\Desktop\" "%databkup%\%backnow%" /s /h /c
xcopy "%USERPROFILE%\Favorites\" "%databkup%\%backnow%" /s /h /c

echo %backnow% Complete

pause
I possibly MISSED some stuff as i did this real quick (I have to go to school)
And i didn't want to TEST myself becouse I didn't want to create the complete filestructure (your folders and files) to test on

edit: I turned echo off, looks prettier this wayThanks,
That helped move it along.  Got up to file below and seems to be working now.  Still tweaking and trying to get the spaces back in the folder names.

Note - had to change date variable for dos folder name.
=====
Backup User Data XP

echo on
cd c:\

rem Get date variables
for /f "tokens=2,3,4 delims=/ " %%a in ('DATE /T') do set date=%%a%%B%%c

rem set variables
set databkup=d:\backup\ScheduledBackupFolder
set backnow=CurrentBackup\%Username%%date%Backup
set backold=OlderBackup

rem Move last backup to Older Backup folder
rmdir "%databkup%\%backold%\" /s /q
xcopy "%databkup%\CurrentBackup\*.*" "%databkup%\%backold%\*.*" /s /h /c /y

rem Backup current My Documents, Desktop and Favorites
rmdir "%databkup%\CurrentBackup\" /s /q
xcopy "%USERPROFILE%\My Documents\*.*" "%databkup%\%backnow%\My Documents\*.*" /s /h /c /y
xcopy "%USERPROFILE%\Desktop\*.*" "%databkup%\%backnow%\Desktop\*.*" /s /h /c /y
xcopy "%USERPROFILE%\Favorites\*.*" "%databkup%\%backnow%\Favorites\*.*" /s /h /c /y

echo %backnow% Complete

pauseI think I got it!! 

Fully customizable bat file to backup/copy just the files and folders I want, and is able to be set as a scheduled task.

=====
Backup User Data XP.bat

echo off
cd c:\

rem Get date variables
for /f "tokens=2,3,4 delims=/ " %%a in ('DATE /T') do set date=%%a-%%b-%%c

rem Set backup folder variables
set databkup=d:\backup\Scheduled Backup Folder
set backnow=Current Backup\%Username% %date%Backup
set backold=Older Backup

rem Set locations to backup
set backloc1=My Documents
set backloc2=Desktop
set backloc3=Favorites

echo.
echo Move last backup to Older Backup folder
rmdir "%databkup%\%backold%\" /s /q
xcopy "%databkup%\Current Backup\*.*" "%databkup%\%backold%\*.*" /s /h /c /q

echo.
echo Backup current %backloc1%, %backloc2%, %backloc3%
rmdir "%databkup%\Current Backup\" /s /q
xcopy "%USERPROFILE%\%backloc1%\*.*" "%databkup%\%backnow%\%backloc1%\*.*" /s /h /c /q
xcopy "%USERPROFILE%\%backloc2%\*.*" "%databkup%\%backnow%\%backloc2%\*.*" /s /h /c /q
xcopy "%USERPROFILE%\%backloc3%\*.*" "%databkup%\%backnow%\%backloc3%\*.*" /s /h /c /q

echo.
echo %backnow% Complete

echo.
pause

387.

Solve : Inventory program in .bat?

Answer»

I wish to create a simple batch FILE for my buisness  that lets me INPUT a part number, name, manufacturer, price and quantitiy. I then want a command that allows me to search the databse for a certain ITEM by name,part number, or manufacturer. I also need a way for the program to subtract frm the quantitiy when i make a sale... I know its compilcated but im familiar with batch, I can make menus and simple scripts to HOLD VARIABLES and recall them. i just dont know how to make the database part... I also need it to be efficient enough to hold around 15,000 items and recall all of them... please help!This sounds more like a school or college project to me. Nobody with a real business would be crazy enough to use a batch file for parts inventory. Nice try though.


388.

Solve : create a menu in dos?

Answer»

I need to create a menu in DOS that looks like the following:

CISS 125
Menu of Options

1. Display all System Files
2. Welcome yourself to the program
3. Display System Information
4. Display Menu Files
5. Exit back to Windows

Can someone please help!! Quote from: Brian223 on December 05, 2010, 08:07:31 PM

I need to create a menu in DOS that looks like the following:

...
5. Exit back to Windows


How would you "exit" DOS to windows?How do you "welcome yourself to the program"?
ECHO OFF

:START
ECHO Menu of Options &&ECHO 1. Display all System Files &&ECHO 2. Welcome yourself to the program &&ECHO 3. Display System Information &&ECHO 4. Display Menu Files &&ECHO 5. Exit back to Windows

SET /p CHOICE=

IF '%CHOICE%' =='1' GOTO ONE
IF '%CHOICE%' =='2' GOTO TWO
IF '%CHOICE%' =='3' GOTO THREE
IF '%CHOICE%' =='4' GOTO FOUR
IF '%CHOICE%' =='5' GOTO FIVE
GOTO :ERROR

:ONE
ECHO You hit One! AWESOME...
GOTO END
:TWO
ECHO You hit Two! AWESOME...
GOTO END
:THREE
ECHO You hit THREE! AWESOME...
GOTO END
:FOUR
ECHO You hit Four! AWESOME...
GOTO END
:FIVE
ECHO You hit Five! AWESOME...
GOTO END
:ERROR
ECHO Invalid Number...
:END
very good... but why the double ampersands? (This isn't Unix)

what should be in place of double ampersands? Quote from: Brian223 on December 06, 2010, 08:25:23 PM
what should be in place of double ampersands?

Single ones.
Hello Salmon,
Are you able to show me how to create a menu in  UNIX?  I need it to look like this:

Menu of Options
1. Display all users in the UNIX system
2. Welcome yourself to the program
3. Display System information
4. Exit back to Windows 
This is your homework, right?

And...

Quote
4. Exit back to Windows 


From Unix? Really?


You went from dos to unix??? Tell your teacher to stay consistent.  Yes this is my homework and may get a bad grade just don't understand. 

THANKS to all who helped Quote from: Salmon Trout on December 06, 2010, 03:40:16 PM
very good... but why the double ampersands? (This isn't Unix)

The double ampersand means if the first one succeed then run the SECOND command. A single ampersand means run the second command even if the first one fails. I usually use two but in this case it could be overkill. Quote from: realgravy on December 08, 2010, 11:57:10 AM
The double ampersand means if the first one succeed then run the second command. A single ampersand means run the second command even if the first one fails. I usually use two but in this case it could be overkill.

I know what a double ampersand does in Windows NT family command scripts.  I cannot SEE the point of USING them after ECHO commands. Quote from: realgravy on December 08, 2010, 11:57:10 AM
I usually use two

Ahh...

Cargo Cult programming.I have from time to time come across code where the writer APPARENTLY wants to "make sure" that something happens (or doesn't happen)... A sort of belt-and-braces approach (braces are what N.Americans call "suspenders") - I think I might have read an article about this on Stack Overflow


389.

Solve : findstr Syntax?

Answer»

In:

Code: [Select]set var=born
echo %var% | findstr /i "or">nul
echo %errorlevel%

The errorlevel echoed is 0, presumably because 'born' contains an 'or'. How do I write the findstr line, so that only exact matches to the full word result in no error?

I have also tried:

Code: [Select]echo %var% | findstr /l /i "or">nul

and

Code: [Select]echo %var% | findstr /i /c:"or">nul
In normal English text the word "or" is both preceded and followed by a space.
  Yes it is. Quote from: gregory on December 13, 2010, 06:59:38 AM

Yes it is.

therefore

Code: [Select]echo %var% | findstr /l /i " or ">nulStill GIVES errorlevel 0 for any word containing 'or'.

Perhaps I EXPLAINED it poorly. Any word that is not exactly 'or', should fail to match and cause an errorlevel of 1. Currently any longer word which contains an 'or' e.g. orion, born, will not set the errorlevel.Seems to work with the /C: switch

Code: [Select]echo off
set var=a star called Orion
echo var=%var%
echo %var% | findstr /i /C:" or ">nul
echo errorlevel=%errorlevel%
echo.
set var=The picture of DORIAN Gray
echo var=%var%
echo %var% | findstr /i /C:" or ">nul
echo errorlevel=%errorlevel%
echo.
set var=red or white
echo var=%var%
echo %var% | findstr /i /C:" or ">nul
echo errorlevel=%errorlevel%
Code: [Select]var=a star called Orion
errorlevel=1

var=The picture of Dorian Gray
errorlevel=1

var=red or white
errorlevel=0
My idea of spaces was a step in the right direction. This is the recommended method from the findstr page at ss64.com.

Finding a string only if surrounded by the standard delimiters (comma , semicolon ; equals = space  tab) therefore find the whole word "or" but not the characters o followed by r in e.g. corn, born, risorgimento, forlorn...

put \< before the search string and \> after it

using or as the search string...

echo %var% | findstr /i "\<or\>"

See here

http://ss64.com/nt/findstr.html

This is a useful site to bookmark.

Thanks a whole bunch guy. I'm very appreciative. That seems to do the trick.

The \< and \> are shown in the help for findstr under the 'Regular expression QUICK reference' section. Just by looking, I would think I needed the /r switch....but you don't.

Anywho, thanks again.
390.

Solve : Batch file logger??

Answer»

Could someone show me a simple 'batch keylogger'? I know it's not a real dangerous keylogger, i just WANT anything that you type in the batch screen be logged into a txt file or something like that. Just wondering if it could work. Thanks I would also like to know if this is possible, can a batch file gather keyboard input without typing in the window? Quote from: shanked on December 15, 2010, 08:28:48 PM

Could someone show me a simple 'batch keylogger'? I know it's not a real dangerous keylogger, i just want anything that you type in the batch screen be logged into a txt file or something like that. Just wondering if it could work. Thanks

You probably could if batch code was a programming language. But it's not, so you can't. You might try one of the Windows script languages, but you'll need access to the Windows API (use a class wrapper). A full service programming language could definitely be USED. Even .Net Framework classes might have something you could use in Powershell or the other .Net languages. Lots of options limited only by your imagination and skill SET.

Quote from: polle123 on December 16, 2010, 05:09:04 AM
I would also like to know if this is possible, can a batch file gather keyboard input without typing in the window?

I'm not understanding.  How would it work to capture keyboard input without typing?

Keyloggers are an invasion of privacy. How would you like someone capturing your keystrokes every time you use the computer?  Quote
I'm not understanding.  How would it work to capture keyboard input without typing?

You DO type, but not in the open prompt. Was wondering if it could be done

And having a keylogger on your computer is just the thing you want if you suspect parents or brothers/sisters going trough your stuffA Keylogger of any "usable" caliber needs to IMPLEMENT a Global Windows hook.

This is something that is not easy to do properly; you can create Windows Hooks in almost any language that can call the API, but in order to create a global hook you need to make a stdcall dll. There are some workarounds, thankfully, that allow you to create and receive Hook events. They are usually quite messy (in any language).

Of course, there are probably a lot of COM and/or .NET components that expose this functionality so you don't have to write your own. But even suggesting it is something batch can or should be able to do is kind of dumb.

Quote from: polle123 on December 16, 2010, 11:50:47 AM
Was wondering if it could be done
No. Not in batch. Quote from: BC_Programmer on December 16, 2010, 11:56:00 AM
No. Not in batch.

meh, expected as muchAre you guys sure? I think I've made something somewhat similar before i just forgot what i did.  I know (somehow) you can put words into a text file (what you type in batch screen) and when you press 'enter' it will move those words into the text file. The thing i'm trying to make is just to update the text file of what they type (such as every letter) or if you cant update every letter, every time you press enter.The only other thing I can think of is the DOS copy con command. This is not a key logger, more of a primitive editor (even more primitive than EDLIN, if that's possible) Copy Con takes no prisoners, you can't edit an existing file and if you make a mistake, you get to start all over again.

Quote
Usage:

copy con test.txt


Finally, a user can create a file using the copy con command as shown above, which creates the test.txt file. Once the above command has been typed in, a user could type in whatever he or she WISHES. When you have completed creating the file, you can save and exit the file by pressing CTRL+Z, which would create ^Z, and then press enter. An easier way to view and edit files in MS-DOS would be to use the edit command.
Source

Why not use an editor like Notepad or even the DOS EDIT?

Good luck.



Quote from: shanked on December 16, 2010, 04:11:39 PM
Are you guys sure? I think I've made something somewhat similar before i just forgot what i did.  I know (somehow) you can put words into a text file (what you type in batch screen) and when you press 'enter' it will move those words into the text file. The thing i'm trying to make is just to update the text file of what they type (such as every letter) or if you cant update every letter, every time you press enter.

yes, but the thing of a keylogger is capturing keyboard input that is NOT typed directly in the prompt but somewhere else, like in a browser (also this would probably be used maliciously)
391.

Solve : How to keep batch file running?

Answer»

Here's the problem.  Scheduled tasks can only be initiated, modified, canceled by an administrator (so I think).  I'll be testing batch files that are supposed to start Excel and ACCESS as scheduled tasks and run some jobs.

How can I set up some sort of batch 'shell' file that is created by the administrator and calls some other batch file that I can modify at will.  The scheduled 'shell' needs to stay alive until some action that I perform allows it to exit (e.g., delete a 'gate' file).  The called batch file that I will modify will run 10-15 minutes.  When it's finished, I'd like to modify it and have it run again.

Hope this is clear enough to get some suggestions.  Thanks. Quote

calls some other batch file that I can modify at will.  The scheduled 'shell' needs to stay alive until some action that I perform allows it to exit (e.g., delete a 'gate' file).

Code: [Select]echo off
call somename.bat
:start
if not exist gatefile.bla goto:eof
other code goes here
sleep 1
goto start

If you don't have the sleep command installed, then you need to download it.

Quote
When it's finished, I'd like to modify it and have it run again.

Not sure what you mean. How do you want it modified?Basically, I want to keep the shell (scheduled task) running but be able to change what the task does without cancelling the scheduled task itself.  This is a testing period, so for example, I may want to have Excel started VIA the scheduled task and have it open a workbook and execute a 'workbook_open' event macro.  while the scheduled task is still active, I may want to have it start Access with an 'Autoexec' macro.

It all goes back to the fact that I have no control over initiating, modifying, cancelling a scheduled task.  I can only request that one be scheduled.  Hence the 'shell' concept where I can then modify the script that is called by it.I am unsure why you need the task scheduler at this point in your development. Why can't you test your batch file(s) from the command prompt until you are satisfied with the results? At that point you can have the administrator put the files directly on the schedule with no need for a "shell".

Batch files do not run any different whether they are started from the command line or the scheduler, but be aware that a batch file will open will open a command window to run. Windows programs (Access or Excel) may also open their own Windows unless the startup macro leaves the VISIBLE property turned off.

Due to the obscurity and obtuseness of some the the batch notation, you're better off keeping your batch files simple and not adding layers of complexity.

Just a thought,

 
I am doing testing via command line and also scheduling my own tasks, but this is on my desktop.  The process will run on a remote server, so file locations, mail servers, etc. will be different.  I don't want to keep requesting changes through the administrator. Quote
The process will run on a remote server, so file locations, mail servers, etc. will be different.

Not knowing any of the details of your operating system or batch files(s), you can make your code as generic as possible and use VARIABLES for specific values based on which system the code is running. For example you can query the %computername% variable and set file locations, mail servers, etc accordingly.

Code: [Select]if %computername% EQU myComputer (
  set accessdb=e:\path\file.mdb
  set excelbook=e:\path\file.xls
)

if %computername% EQU Server (
  set accessdb=x:\path\file.mdb
  set excelbook=x:\path\file.xls
)

In reality you will probably have more variables, but I'm guessing you can see where this is going.

Make sure the job can run from a shortcut or the command line on both your local machine and the server. Putting the job on the scheduler should be the final step in the process, not the first step.

Good luck.  Good suggestion.  I think I'm getting close to what I need. Next step is to request scheduled task from administrator.
392.

Solve : add result of a command in variable?

Answer» HI, i am NEW in this forum and i need to know
How to add  the result of a command in variable?

thx
 
What do you mean by result ? the errorlevel ? a PRINTED line of TEXT ?C:\test>type result.bat
ECHO off
set /a result=0
:loop
set /a result=%result% + 1
if %result%==10 goto end
goto loop
:end
echo result=%result%
echo bye

Output:

C:\test>result.bat
result=10
bye

C:\test>
____________________________________


C:\test>type result.bat
echo off
set /a result=0
:loop
set /a result=%result% + 1
if %result%==%1 goto end
goto loop
:end
echo result=%result%
echo bye

Output:

C:\test>result.bat 15
result=15
bye

C:\test>result.bat 4
result=4
bye

C:\test>
393.

Solve : Please help with COPY/RENAME command?

Answer»

Hello,

Trying to get back into writing batch files, been several years. I have several files in a folder that I would like to copy/rename from one destination to another. The file names VARY, here are a few examples of the SOURCE file names:

200167-010-Model.jpg
200169-008M-Model.jpg
200169-012C WITH LEG LEAD-Model.jpg

I would like the destination file names to be the same, with the exception of removing "-Model". From the source files above, the destination file names would be:

200167-010.jpg
200169-008M.jpg
200169-012C WITH LEG LEAD.jpg


In all cases the "-Model" in the source name is at the end (IE. *-Model.jpg).


Thanks in advance for any help,
ChiSoxFanThis little snippet will simply list the copy operations but not actually perform them. When you are satisfied with the results, remove the word echo from the highlighted line. I named the source folder source, and the target folder target, change as necessary.

Quote

echo off
setlocal enabledelayedexpansion

for /f "tokens=* delims=" %%i in ('dir c:\source /b') do (
  set newName=%%i
  set newName=!newName:-model=!
  echo copy "c:\source\%%i" "c:\target\!newName!"


Good luck. 
C:\test>TYPE  chi.bat
echo off
setlocal enabledelayedexpansion

for /f "delims=" %%i in ('dir c:\test\source\*.jpg /b') do (
  set newName=%%i
echo newname=!newname!
  set newName=!newName:-model=!
echo newname=!newname!
 copy "c:\test\source\%%i" "c:\test\target\!newName!"

)
cd c:\test\target\
dir  *.jpg

Output:

C:\test> chi.bat
newname=200167-010-Model.jpg
newname=200167-010.jpg
        1 file(s) copied.
newname=200169-008M-Model.jpg
newname=200169-008M.jpg
        1 file(s) copied.
 Volume in drive C has no label.
 Volume Serial Number is 0652-E41D

 Directory of c:\test\target

12/15/2010  08:42 PM                 9 200167-010.jpg
12/15/2010  08:43 PM                 9 200169-008M.jpg
               2 File(s)             18 bytes
               0 Dir(s)  291,049,746,432 bytes free
C:\test>That worked great.

Thanks to both of you.

394.

Solve : Duplicate files with alternate name from list??

Answer»

Trying to figure out a way to do this and wondering if it can be done with a batch or other script. Trying to find a way to take a bunch of files named such as 24.doc  37.doc  44.doc   45.doc and on and on and create duplicate copies of these files with file names in order from a list.

So

24 = John Meyers
37 = Steve Grell
44 = Sue Bruel
45 = Amy Heisler

and I have a query that is like so in order that matches up with the numeric order of files that exist ( there are numeric gaps as when names were deleted, the numbers were deleted and never reused, but the names remaining in column 2 match up with that in column 1's number index.)

John Meyers
Steve Grell
Sue Bruel
Amy Heisler

The 15 Gigs of Documents NUMBERED 24 thru 63542, I have a table that associates that 24 is John M and 37 is Steve G ...etc. so I am able to create a query in order that matches up with the file names in numeric order so that the CORRECT name gets ASSOCIATED with the correct file. Now the problem I am trying to solve is how to read in this list from the query and perform a COPY routine that will go through all files in numeric order and create copies of these files with the correct Names.doc in addition to retaining the original Number.doc by reading in the names from a list that can be as simple as a Names.txt file in raw ascii  .

Stumped with this, I checked into software out there to see if anyone has created any tools to perform such actions and even better file rename doesnt have a feature that will help me with this, so I figured I'd post here to see if anyone has SUGGESTIONS or might be able to share some coding that is beyond my level of coding in which this might be achieved through a batch or VB script or other means.

In the end basically file named 24.doc is now duplicated as John Meyers.doc and file 37.doc is duplicated as Steve Grell.doc ( so " " will likely be needed in the routine because of spaces in file names if the copy routine is utilized.)
If you had a text file, say a csv which looked like this

24,John Meyers
37,Steve Grell
44,Sue Bruel
45,Amy Heisler

etc

it would be easy to make a batch script to copy 24.doc to John Meyers.doc and so on.

Do you, or can you, have such a file?


Yes i could create one quickly through a query for columns number and name in that csv formatQueryList.csv

Code: [Select]24,John Meyers
37,Steve Grell
44,Sue Bruel
45,Amy Heisler
55,Joe Smith
60,Bill Brown
66,Walter Briscoe
74,Mary Ann Jones
994,Sidonia Walcott
11234,Anne-Marie Bolinski

batch script

Code: [Select]echo off
for /f "tokens=1* delims=," %%A in (QueryList.csv) do (
    echo Copy "%%A.doc" "%%B.doc"
    )

output

Code: [Select]Copy "24.doc" "John Meyers.doc"
Copy "37.doc" "Steve Grell.doc"
Copy "44.doc" "Sue Bruel.doc"
Copy "45.doc" "Amy Heisler.doc"
Copy "55.doc" "Joe Smith.doc"
Copy "60.doc" "Bill Brown.doc"
Copy "66.doc" "Walter Briscoe.doc"
Copy "74.doc" "Mary Ann Jones.doc"
Copy "994.doc" "Sidonia Walcott.doc"
Copy "11234.doc" "Anne-Marie Bolinski.doc"
When you are HAPPY that it works as you require change

this

echo Copy "%%A.doc" "%%B.doc"

to this

Copy "%%A.doc" "%%B.doc"

Awesome!  Many Thanks!!!

Impressed with how small that script is and it works perfect!!!!

395.

Solve : Help! - Bloe Screen - Dos Mode - Access Denied?

Answer»

Help!

I got a blue screen, tried F8, tried safe-mode startup - went back to blue screen, finally MANAGED to use disk to reboot for repair, went into MS Dos screen, ended up with c:\ in black screen. The only thing I could do is chkdisk, I cannot fdisk. I can access other partition and go into c:\windows but cannot access c:\docume~1\phillip\desktop (trying to save DATA on my desktop).

Kindly help

Phillip
Slave Drive Info...

The safe way to retrieve your data...including pics and videos on how to do it properly.1) Do system restore to a day when all was well?

 %systemroot%\system32\restore\rstrui.exe

C:\>cd \
C:\>dir /s rstrui.exe
  Directory of C:\Windows\System32

07/13/2009  07:14 PM           262,656 rstrui.exe
               1 File(s)        262,656 bytes

2) Run your anti virus and cleanup programs?

3)Are you using XP?

396.

Solve : Make a bat file to login on a website?

Answer»

Hi
Can any one help me, i need a bat file or scrips to VIA TIMER to START firefox and a special website and then log in one the website, the website is a HTTPS a site, NOTE! it is legal

Please helpMore info is needed.
What OS are you using?
What prevents you from logging on automatically?
Is this to be a batch to log on on over the LAN? I mean are you going to be on computer B and log compeer A on a web site using Firefox on computer A while you are at the command prompt on computer B?
I am guessing, but that is the only way it would make sense. I guess.
This does not answer your question but might get you STARTED.

Code: [Select]start  "C:\Program Files\Internet Explorer\iexplorer.exe" http://ww2.cox.com/To Log on to a website you will need more than just batch using a START IE "URL" process, but a macro that can handle passing mouse position and keystrokes. I use Jitbit Macro Creator for these types of automated tasks. Cheap and easy to use! Also you can create POWERFUL exe's out of it!!!

397.

Solve : Choosing random words?

Answer»

How would you choose a random word from 'lists' of words?

For example...

List number one will be:
-He
-She
-It

List number two:
-swam
-jumped
-screamed

It will PICK one random word from list number one.
On the second list...

If the word 'swam' is chosen it goes to a list specified list for 'swam'.
For example, if 'swam' is chosen, the next random word will be either:
-fast
-slow
-proudly

If 'jumped' is chosen, the next random word will be either:
-high
-far
-low

If 'screamed' is chosen, the next random word will be either:
-loud
-quietly
-uncontrollably

Then in the end it will put the words together such as...

She jumped high.

Just an example ^,  but I'm wondering how i can do this.  Thanks
So, what you'll first need is a file with a list of words, in my code it will be called TOPlist.txt . Then, for each word in any list, you need a file called WORDlist.txt (word being substituted for the actual word).

The script will only display the sentence when it has reached a word with no sub-list.

Code: [Select]echo off
setlocal enabledelayedexpansion
set rnd=0
set word0=TOP
:loop
If exist !word%rnd%!list.txt (
call :words
goto loop
) else (
echo %display%
pause
)
exit

:words
set count=0
for /f "delims=" %%A in (!word%rnd%!list.txt) do (
set word!count!=%%A
set /a count+=1
)
set /a rnd=%random%%%%count%
set display=%display%!word%rnd%! How does reply 1 or reply 2 help? Quote from: Frankfoley on December 20, 2010, 06:39:58 AM

How does reply 1 or reply 2 help?
How does making posts like that help? I gave a code which should help the OP. Quote from: Helpmeh on December 20, 2010, 07:57:52 AM
How does making posts like that help? I gave a code which should help the OP.

Helpmeh: It's Bill again. Quote from: BC_Programmer on December 20, 2010, 07:59:37 AM
Helpmeh: It's Bill again.

He is always easy to spot.
An alternative... a limitation is that for the adverbs, you have to have the same number for each verb. Also, a grammar point, in the examples given, "slow" and "loud" are incorrect in standard English - they are verbs, the correct adverbs are slowly and loudly.

Code: [Select]echo off
setlocal enabledelayedexpansion

rem I know He, It, They are pronouns; it makes the code simpler
rem if I call them nouns here
rem noun He
rem noun It
rem noun She
rem noun John
rem noun Mary
rem noun They
rem 5 nouns or pronouns


rem verb swam
rem verb jumped
rem verb screamed
rem verb walked
rem verb smiled
rem 5 verbs

rem adverb swam fast
rem adverb swam slowly
rem adverb swam proudly
rem adverb swam WELL
rem adverb swam badly

rem adverb jumped high
rem adverb jumped far
rem adverb jumped low
rem adverb jumped up
rem adverb jumped down

rem adverb screamed loudly             
rem adverb screamed quietly       
rem adverb screamed uncontrollably
rem adverb screamed instantly
rem adverb screamed alarmingly

rem adverb walked quickly
rem adverb walked strangely
rem adverb walked often
rem adverb walked seldom
rem adverb walked briskly

rem adverb smiled sweetly
rem adverb smiled readily
rem adverb smiled dourly
rem adverb smiled oddly
rem adverb smiled happily
rem 5 adverbs for each verb

set /a nrand=%random%%%5+1
set /a vrand=%random%%%5+1
set /a arand=%random%%%5+1

set number=1
for /f "tokens=1-3 delims= " %%N in ( ' type "%0" ^| find "rem noun" ^| find /v "type" ' ) do (
if !number! equ %nrand% set noun=%%P
set /a number+=1
)
set number=1
for /f "tokens=1-3 delims= " %%V in ( ' type "%0" ^| find "rem verb" ^| find /v "type" ' ) do (
if !number! equ %vrand% set verb=%%X
set /a number+=1
)
set number=1
for /f "tokens=1-4 delims= " %%A in ( ' type "%0" ^| find "rem adverb %verb%" ^| find /v "type" ' ) do (
if !number! equ %arand% set adverb=%%D
set /a number+=1
)
set phrase=%noun%%verb%%adverb%
echo %phrase%

Code: [Select]S:\Test\random-word>for /l %Q in (1,1,30) do rand-phrase.bat
John screamed loudly
John screamed uncontrollably
Mary screamed alarmingly
He swam fast
Mary swam well
She swam well
John smiled oddly
John swam proudly
He smiled oddly
She jumped high
Mary walked quickly
She walked seldom
He screamed loudly
She jumped far
It jumped down
Mary swam well
It walked seldom
It smiled sweetly
It walked quickly
She swam badly
John smiled dourly
John swam well
She walked often
She jumped up
It walked strangely
She screamed alarmingly
She smiled sweetly
She screamed loudly
It jumped up
It smiled dourlySalmon Trout, The Sockpuppet, strikes again.

Always easy to spot.


Salmon Trout and Shanked  are the same person
Quote from: Helpmeh on December 20, 2010, 07:57:52 AM
I gave a code which should help the OP.

How does your code  help? Your code generates no output.  Your code does nothing.

Look at Samon Trout's code for the answer.oh Bill, you crazy insane fool.

See people, this is what FORTRAN does to people. Dijkstra noted that BASIC mutilated minds but apparently so too does long time exposure to FORTRAN.


Quote from: bobhoward on December 20, 2010, 12:05:00 PM
How does your code  help? Your code generates no output.  Your code does nothing.

His code works fine. Perhaps you didn't read the instructions. Not that it matters, you clearly cannot read the various hints by the forum to go away, such as, for example, being banned countless number of times.

preemptive response fro Bill; will probably be something to the effect of apologizing to the OP for his thread going off topic and then wishing him well getting help, or some other completely random muttering. Possibly accompanied by asking me where my code for this issue is. Quote from: BC_Programmer on December 20, 2010, 12:16:23 PM

His code works fine. Perhaps you didn't read the instructions.

preemptive response fro Bill; will probably be something to the effect of apologizing to the OP for his thread going off topic and then wishing him well getting help, or some other completely random muttering. Possibly accompanied by asking me where my code for this issue is.

To:
BC, The Computer Dilettante who has  never had a creative thought in his life.

Thanks for the help.

Please provide the output for Helpmeh's codeOuch! My precious feelings! Oh how will I ever recover from the death blow that the great Bill has caused to my ego.

Although the fact that simple directions cannot be followed, and he is essentially asking me to perform the very simple, grade-school task of following some of the relatively simple STEPS that Helpmeh provides for running his scripts sort of ruins the ATTEMPT at an insult.

Better luck next time perhaps.

Quote from: bobhoward on December 20, 2010, 12:05:00 PM
Your code generates no output.

Bill is crazier than a whole barrel of Tea Party members.
Quote from: BC_Programmer on December 20, 2010, 12:43:18 PM
Although the fact that simple directions cannot be followed, and he is essentially asking me to perform the very simple, grade-school task of following some of the relatively simple steps that Helpmeh provides for running his scripts sort of ruins the attempt at an insult.


BC, The Computer Dilettante:

Where is Helpmeh's code and output?  Some the readers here are gradeschool children and new to computers.

Not  only is BC a Computer Dilettante but BC is an expert at evasion, double talk and long nonsense posts.
Code: [Select]D:\testhm>runhm

-----------------------------
atelist.txt:
-----------------------------
quickly
deliberately
-----------------------------
helist.txt:
-----------------------------
Ate
Left
-----------------------------
jumpedlist.txt:
-----------------------------
quickly

-----------------------------
leftlist.txt:
-----------------------------
quickly
deliberately
-----------------------------
shelist.txt:
-----------------------------
jumped
slowly
-----------------------------
slowlylist.txt:
-----------------------------
ate
left
-----------------------------
TOPlist.txt:
-----------------------------
He
She
Result:
He Left quickly

D:\testhm>

also:

Quote
BC, The Computer Dilettante:

That shouldn't be capitalized; it should be "BC, the computer dilettante".

oh yes, Should post the runhm.bat program as well:


Code: [Select]echo off
for %%P in (*.txt) do (
echo.
echo -----------------------------
echo %%P:
echo -----------------------------
type %%P
)
echo.
echo Result:
echo.
hm


398.

Solve : Access Databse from cmd?

Answer»

Hi Everyone,

I have tried my best to search for this problem I'm sure I'm not the only out there with this problem but i just dint seem to have any luck.

I have a certain access database originally 2003 that when run from the cmd line PRODUCES a graphical windows error "file not found" that halts the batch file. This error is graphical and I cannot suppress it from the cmd line. The file is there and runs... Access LOADS up does its stuff and its only on the exit of access that the error occurs. This does not happen when double clicking the file through explorer.

I have done the following with no success

Converting to 2007 database
Renaming files to no spaces
Running with quotes around file names
Piping cmd output to file with >
Changing Directory
Renaming Directory for no spaces
Disabling compact on close
Using quit with SaveAll and Exit
CTTY nul - (this is not a recognised cmd on my system)
Settings permissions for Everyone full access rights
preceding the opening of the file with start



Below is the batch file. The error occurs for each file but they are copies of each other except for minor alterations.

Code: [Select]cd C:\TextAnywhere
LutonAuto.accdb
BedfordAuto.accdb
RushdenAuto.accdb
cd dist
java -jar "Text Anywhere.jar"
pause
I am running on Windows 2003 server as Administrator with Office 2007. All updates patches installed inc the latest office service pack. The access databases do some sql querying and output results as csv. I made a java app to read these csv files, connect to a txt gateway and send customers appointment reminders. The file not found error is stopping this being automated.

Any feedback or suggestions would be much welcomed!

Cheers
Tim- BUMP

Have also tried coding a wait for ten seconds between writing the file and the database closing. No luck though Weirdly if i have a message box between them no errors occur, this is no good though as i need it automated!Screen print -

[recovering disk space - old attachment deleted by admin]The csv file is definitely written by the macro before it closes. I put a 30second wait after writing and checked the RESULT then. Just tried it on another machine and same thing, also tried disabling the virus scanner. The only thing i can think of is the database is SOMEHOW corrupt (unlikley) or that the command im using to quit is not correct.

VBA quitting - Code: [Select]Application.QuitMacro quitting - Code: [Select]Quit with options exit and saveall tried

Though i though the above where pretty standard and I have used them before with no problems at all. Do they look correct to everyone?

Cheers

TimHave you considered exporting it (dumping it to a sql file) then importing it into mySQL to see if you have better luck at the command PROMPT. I have had better luck personally from mySQL when running processes at console mode and through batched and scripted methods. I am using mySQL 5.1 and havent had any problems with batches and automated processes that are in a feedback loop of reads and writes etc. *There is a checkbox during the mySQL installation that enables console command line interfacing with mySQL. I think mySQL will solve your issue possibly.

399.

Solve : Restore Files from DOS Backup?

Answer»

I need to recover a set of document files that were backed up in June 1995 using the native BACKUP utility in either DOS 5/6 or perhaps the backup utility in Windows 3.1. 

I do not know the brand (e.g., MSDOS or DRDOS, etc.) or the percise version of DOS was used to make the backup.  The 3.5" floppies that I have includes two files (one each disc): cc50625a.001 (1,424 kb) & cc50625a.002 (1,424 kb); I have these files backed up on hard drive.

I have limited time and resources to try to find the right solution to "unlock" and extract the files.  I am hoping that someone has the knowledge to help.  I'd be willing to pay up to $40 to anyone (VIA PayPal) that can extract the files.Are you sure its just 2 disks? USUALLY in a spanned backup you have the last disk with contents smaller than the maximum storage capacity; such as 3 disks where disk 1 and disk 2 are maximum capacity and disk 3 is say 780k of 1.44MB

Most utilities that I know of require the full backup set to retrieve a single file even if the single file resided on disk 1 and there are 3 disks. It assembles the spanned data and decompresses it to readable file and folder contents.

Due to legal reasons dealing with unknown data origin, many will AVOID getting directly involved in doing the work for you here. Here we offer help and advice and you take the knowledge and code etc that we provide and you have to take that and edit if needed and execute it on your own. You might be able to bring the disks to a computer shop and have them check them out. They are probably too old to have Metadata to give insight as to what they were created with to then know how to expand them, however you could right-click on the backup files and select properties and then summary to see if they have metadata. I am pretty sure 1995 pre-dates metadata info associated with files though.

400.

Solve : Echo Message Based on most recent file extension?

Answer»

I need to do a sort of a directory based on time/extension.  If the most recent FILE extension is XXX then I want to display a message.  If the most recent file extension is YYY then I was to display a different message.  Using Windows XP.

Example -

File1.XXX - 12/17/2010 11:00 am
File2.YYY - 12/15/2010  12:15 pm

Message - "XXX is the most recent file extension.

Any ideas would be APPRECIATED.  Thanks! CODE: [Select]echo off
for /f "delims=" %%A in ('dir /b /od /a-d ^| find /v "%~nx0"') do set lastext=%%~xA
if /i "%lastext%"==".XXX" goto xxx
if /i "%lastext%"==".YYY" goto yyy
goto neither
:xxx
echo last file had extension xxx
goto END
:yyy
echo Last file had extension yyy
goto end
:neither
echo Last file had neither xxx nor yyy extension
:end
echo Finished


That answer was awesome, fast, AND it worked!!  Thank you very much.  Without getting too mushy, it's people like you that make the internet cool  .  Thanks again.