'for' command

Status
Not open for further replies.

AmmonSalmo

Seniorius Lurkius
5
(This is my first post...If you guys can help me out I promise to contribute to this forum!)

I've recently dived into the world of batch file programming, and though head-bangingly tedious trial-and-error have been slowly mastering the use of batch commands.

Yes I am a newb. As nub as they come. In my infantile audacity I have resolved to knock on the programming Gods door in the hopes that he will listen...

---

The operation I am trying to create is simple;

-

A list of documents (a text file, containing the names of other text files) has been created and should be operated upon in the order they appear. (for)

The operation must read a document and determine if it contains a certain phrase or string (findstr)

If the above operation is executed without error, then a variable will be set to [Y] If there is an error, the variable will be set to [N] (set var)

The above variable should then be recorded into a separate document; this document will eventually contain all the results of the batch operation.

The operation, continuing the original [for] command will repeat until all documents have been operated upon.

---

So far I have individual pieces of this thing working. To find text and set the variable accordingly I have:


findstr /m "[certain text]"
if %errorlevel%==0 (
set var=Y
)
if %errorlevel%==1 (
set var=N
)


To record the results of [findstr]:

echo %var%>>[a file containing the results].txt

However, I cannot seem to implement the [for] command to continue the operation past the first document in the list. As trying as I might, I am rewarded with a blank cmd screen or an error message.

---

This is my complication. Please help. If you need any more information, I will be promptly and readily willing to give it!

Thank you in advance!
 

AmmonSalmo

Seniorius Lurkius
5
I dont believe formatting is the error here, here is my [for] string:

for /F "delims=;" %%I in ([the file list].txt) do goto ACTIONS "%%I"

:ACTIONS
[actions]


[actions] is the findstr and set var strings posted above. When I do this, the "results" file just says...

ECHO is ON.

Strange, as when I run the findstr and setvar commands without for, it works perfectly...
 

devjames

Wise, Aged Ars Veteran
107
You've got a couple of problems. The first thing you need to do is use the help system. the command 'help for' is equivalent to 'for /?' for those commands that are part of cmd.exe.

There are multiple second things. ;v)

First, get in the habit of strarting your batch files like this:
Code:
@echo off

setlocal enableextensions enabledelayedexpansion

You seem to have a couple of for problems. First, variable substitution happens at the time that the cmd.exe parser hits the line to execute. The for command is evaluated, then the loop is run. So, %myvar% is evaluated when the for loop is encountered, not each time through the loop. Here's an example:

Code:
setlocal enableextensions enabledeleyedexpansion

set myvar=0
for /l %%i in (1,1,5) do set myvar=%%i && echo %myvar% = %%i

Doesn't look right because %myvar% is only evaluated once. You need delayed expansion of variables like this:
Code:
setlocal enabledextensions enabledelayedexpansion

set myvar=0
for /l %%i in (1,1,5) do set myvar=%%i && echo !myvar! = %%i

See?

You can execute multiple statements with && (and maybe ||, I'm on Linux right now) but you need ( ) to extend over multiple lines, like this:

Code:
setlocal enableextensions enabledelayedexpansion

set myvar=0
for /l %%i in (1,1,5) do (
set myvar=%%i
echo !myvar! = %%i
)

Creating variables in ( ) and having them exist outside that block can be a little tricky, so I usually declare and initialize variables outside the block.

I left off the @echo off so that you can see the commands execute as they are evaluated. If you start your .cmd file with @echo off you can quite easily disable that by making the line begin with :: like this ::mad:echo off. Remove the :: for the @echo off to take effect again.

Subroutines can be created (see 'help call') and passed parameters and that can make your for loops a little nicer:
Code:
:: do this 5 times.
for /l %%i in (1,1,5) do call :myloop %%i

:: return to outer level
goto :eof

:myloop
:: set all new vars to local scope
setlocal
:: %1 (first parameter) is passed to us

echo we were passed %1
endlocal
:: return to outer level
goto :eof

You eventually want something that looks a bit like this:
Code:
for /f tokens=";" %%i in (list_of_files.txt) do call :checkit "%%i"
goto :eof

:checkit
setlocal
set flagvar=N
:: the " around %1 may not be needed, use a file name
:: with embedded spaces to see.
findstr /m "some text string" "%1"
if ERRORLEVEL 1 (
set flagvar=N
) else (
set flagvar=Y
)

if /i [%flagvar%]==[y] echo found it! >>list_of_files.log
endlocal
goto :eof

Extra points if you figure out why the [] can be needed around %flagvar%.

Hope this helps a bit. If you try to write some code and have further problems post what you've written and maybe we can help.

EDITS: some fixes, some typos. nothing big.
EDIT2:
Your code suffers from the 'creating vars in ( ) causes problems' I mentioned above. Since your flag variable didn't originally exist outside of the ( ) block, but was created within the block, then it went out of scope with the ( ) block. The ( ) create a "mini-cmd.exe" for the code within the ( ). That has _odd_ consequences.
 

AmmonSalmo

Seniorius Lurkius
5
Thank you devjames, I can tell you put considerable effort into that post. Here is the modified code

Code:
for /f tokens=";" %%i in (filelist.txt) do call :checkit "%%i"
goto :eof

:checkit
setlocal
set flagvar=N
findstr /m "hello_there" "%1"
if ERRORLEVEL 1 (
set flagvar=N
) else (
set flagvar=Y
)

if /i [%flagvar%]==[y] echo found it! >>results.txt
endlocal
goto :eof


However, I wish I could say it worked. When saved in batch format and executed, a cmd window blinks and the program ends. When executed from the command prompt:

Code:
C:\Users\[me]\Desktop>for /f tokens=";" %i in (filelist.txt) do call :checkit
 "%i"

C:\Users\[me]\Desktop>

And the 'results' file is bone dry. Not even an error message.

Maybe you would like to take a look at it yourself? I have included a download link to a file that contains the bat, 4 example files, the filelist, and the results file.

http://www.mediafire.com/?dp83r5ry1jj4bg5

As for the brackets, [flagvar] existence is in question. And just curious, why should [goto :eof] be included on the second line?

In either case, thanks for your massive contribution! I want you to know it has not gone unappreciated!
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
AmmonSalmo":2ri3h1ew said:
I apologize for not possessing the knowledge to do such a thing.

HALP!
No problem. 90% of the developers in my office don't know the first thing about powershell and our company practically wrote the damn thing ;)

First of all, you must understand where powershell came from. Windows has always had tremendously powerful scripting ability with Windows Scripting Host. You can script darn near everything. Even mouse movements! Unfortunately, most of this functionality was via scripting COM objects. It was not part of the command-line. Greybeards never took to it.

Black hats, on the other hand, cozied right on up to WSH and had babies with it. They'd attach JessicaAlbaNaked.jpg.vbs to an email and people would double-click on it, proceeding to curse WSH for infecting them and not showing them Jessica Alba sans clothing (unless the black hats were kind and at least included ASCII pron).

So Microsoft went off the fucking ranch crazy the other direction when making powershell. Powershell scripts (.PS1 extension) do not execute when you double-click on them (that's good). However, they also don't run at all unless they're signed by a trusted signer, by default. Are *you* going to sign your scripts? I don't think so. In order to run powershell scripts on your computer, you therefore have to run the following command in a powershell prompt running as administrator:
Code:
Set-ExecutionPolicy Unrestricted
You can now run PS1 scripts.
Code:
# name it hello.ps1 and run it as .\hello.ps1 from a powershell prompt
$now = [DateTime]::Now.ToString("U")
Write-Host "Hello.  now=$now" -ForegroundColor Magenta
Now, just like UNIX shells and .BAT, the command-line *is* the scripting language. Anything you want to try out in a script, you can try out on the command-line to practice. If you right-click->Edit a .PS1 script, it will bring it up in the Powershell ISE (Integrated Scripting Environment), which is quite good.

Unlike UNIX where everything is a string, everything in powershell is an object. Objects can be converted to strings when you need to. It takes a little getting used to, but it puts the "power" in powershell.

You can find plenty of good powershell tutorials on the web.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
I'm not sure I understand your OP requirements fully, but here's a completely untested (even for correct syntax) stab at your problem in powershell, assuming your task is actually
1) there exists a file containing a list of other files
2) for each file in this list, you want to record whether the file contains a certain string
3) I'm assuming "True" and "False" are acceptable substitutes for "Y" and "N"

Code:
# Usage: whatever.ps1 -DocumentListFile list_of_docs.txt 
                      -MatchesFile matches.csv 
                      -SearchText "[certain text]"

# define the parameters the script takes
# these will automatically TAB-complete on the command-line!
param([string]$DocumentListFile, [string]$MatchesFile, [string]$SearchText)

# output headers to the output file
"FileName,IsMatch" | Out-File -FilePath $MatchesFile 

Get-Content $DocumentListFile | ForEach-Object {
  # $_ contains a line of text from the document list file
  $fileToScan = $_
  $isMatch= Select-String $fileToScan -Pattern $SearchText -Quiet
  
  # output "<filename>:True|False" to output file
  "$fileToScan,$isMatch" | Out-File $MatchesFile -Append
}

Now the more powershell-ish way would be to output the filename and isMatch on the output pipeline and let the user pipe it to Export-Csv if they wanted to save it to a file.
 

devjames

Wise, Aged Ars Veteran
107
This code:
Code:
@echo off
:: delete the results file so that subsequent runs don't confuse us
del results.txt >nul 2>&1

:: we need the "delims=;" option because the input file has a useless
:: ; trailing the file name.
:: if the file names contain spaces, however, we must do the for differently.
for /f "delims=;" %%i in (filelist.txt) do call :checkit "%%i"

:: check the results
echo Results.txt:
type results.txt

:: if we don't goto :eof here then we fall through :checkit one more time.
goto :eof

:checkit
setlocal
set flagvar=N

:: we don't need to "%1" here because the "s are passed in with
:: the argument from the for call.
findstr /m "hello_there" %1
if ERRORLEVEL 1 (
set flagvar=N
) else (
set flagvar=Y
)

if /i [%flagvar%]==[y] echo found it in %1! >>results.txt
endlocal
goto :eof

results in this (file setup included for example):
Code:
C:\data\workingcopies ()
>echo hello_there >afile.txt

C:\data\workingcopies ()
>echo hi_there >bfile.txt

C:\data\workingcopies ()
>echo afile.txt; >filelist.txt

C:\data\workingcopies ()
>echo bfile.txt; >>filelist.txt

C:\data\workingcopies ()
>astest.cmd
afile.txt
Results.txt:
found it in "afile.txt"!

C:\data\workingcopies ()
>

The line that only contains the txt 'afile.txt' is the output of the find /m (print file name option) line. To do
away with output call it like I did the 'del' command. 'find /m "hello_there" "afile.txt" >nul 2>&1' would redirect standard output (>) to nul and redirect standard error (2>) to whatever standard output is directed to, in this case nul.

The reason that your 'for ... call :checkit ...' from the command line did nothing is that :checkit only exists while the batch file is running. Technically, the 'scope' of :checkit is limited to the batch file containing it.

Get in the habit of sprinkling 'echo' statements liberally through your batch files for debugging. The 'pause' command is good, too.

As an example:
Code:
for /f %i in (filelist.txt) do echo call :checkit %i
would emit ':checkit blahblah' for each line of filelist.txt where blahblah is the line itself. The output of
Code:
for /f %i in (filelist.txt) do echo %i
would be each line of the file. Well, technically, the first token of each line of the file based upon the standard delimiters. Check out 'help for' for "tokens=" and "delims=" option for actually getting the entire line in all circumstances. That would look something like this:
Code:
for /f "tokens=1* delims=;" %%i in (filelist.txt) do call :checkit %%i;%%j

EDIT: Added comment on redirection of standard output ( > or 1>) and standard error (2>).
EDIT2: Added the "tokens= delims=" stuff.
 

AmmonSalmo

Seniorius Lurkius
5
devjames, I could just about kiss you. It works like clockwork, and I've written one nearly like it and its just as good.

More importantly, I learned a lot about batch writing (and learned how much I still have left to learn...) You've been very instructive through this process and I thank you for that!

Pont, thanks for your input as well. In the past I've dabbled in Java just to see what its like and have since been growing an interest in learning PowerShell. I will definitely look into it in the near future!

I have a feeling this will not be my first question to the boards (oh no!), but I promise to contribute as much as I can as I get a little better at this stuff...

THANK YOU!
 

MilleniX

Ars Tribunus Angusticlavius
8,138
Subscriptor++
Ammon: Welcome to the forum, and good on you for posting a decent question and sticking around to work out a solution with people. If you want to maximize your learning while getting help from others, this is a great article. It sounds like you've got most of the fundamentals in place, but it pays to be conscious of what they are.

Phil
 

daishi

Ars Legatus Legionis
10,387
Really take the time to learn powershell, you will save yourself so much time in the long run. I wrote some scripts last year for our unattended installation for our images (using netdom and batch commands) and I just went back and rewrote the entire thing in powershell and added some extra features we needed (like logging things to an SQLdatabase when the machine starts up the first time and logging the result of the scripts to a custom event log) and it was dead simple. Today I just figured out how to enable psremoting against a block of machines in our organization so I can push out some fixes (via invoke-command) for some odd issues that we been having crop up. Bigger project I am working on is to create some data reporting tools since my boss seems to come to me with interesting metric requests at the last minute and we have data scattered in 10 different databases/excel spread sheets/etc.

TLDR. powershell is really cool.
 
Status
Not open for further replies.