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.

1101.

Solve : Open .pdfs at same time?

Answer»

I would like a batch FILE that SELECTS all .pdf files in a folder and then presses the enter KEY which will open those files in Adobe.

I have the following line:

for %%v in (*.pdf) do "%%v" 

but what this does is open adobe and the first file in the folder, but pauses until I close adobe, then it moves on and re-opens adobe with
the second file.

What could I do to open one instance of adobe, but open all the .pdf files at once? CODE: [SELECT]for %%v in (*.pdf) do start "" "%%v" That did it!  Thanks!

1102.

Solve : How can i change this batch??

Answer»

i SAW this batch file on DosTips

Code: [Select]setlocal enableextensions disabledelayedexpansion
   
set SEARCH1=name
set REPLACE1=ename
set SEARCH2=sal
set REPLACE2=esal

FOR %%F IN ( file1.TXT file2.txt ) DO (   

    for /f "delims=" %%i in ('type "%%F" ^& break ^> "%%F" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:%SEARCH1%=%REPLACE1%!"
      set "line=!line:%SEARCH2%=%REPLACE2%!"
        >>"%%F" echo !line!
        endlocal
    )
)
this is update (find-replace) word in text
i wanna different...
i wanna delete ALL line

source text :
This is first line
long winter DAYS coming
And waiting sunshine

i will search "winter" words in txt files.. and delete complately that line...

result text :
This is first line

And waiting sunshine


how i can do ?
thx Quote from: TosunPASA on December 10, 2016, 06:38:54 PM

i saw this batch file on DosTips
Then why don't you ask the question on the DosTips forums?
1103.

Solve : Baruch to replace space in file name with underscore.?

Answer»

Baruch to replace space in file name with underscore.
OK,I already did it.   
But I was wondering how you would do it.
Here is the problem.Some utilities s used for batch programming don't do well with spaces in file names. Unless you put quotes around everything.
For me,I would rather have underscores and forget about the nice way spaces look in file names. Just a PERSONAL quirk. So I renamed any file-name  with a space to have a underscore character instead.
The method took me about an hour while working with another problem.  But I only had 25 file names. It should not have taken that long. What would I doif EVER  do  if I had 200 names with spaces?
So, my question is : How would you rename all files with space in the name to have only an underscore a dash instead?
Some sample names in a single directory::
Code: [Select]My Dog and Cat.txt
New Phone .txt
NoSpaceHere.txt
west sunset.txt
Lost and found from BACK yard.txtAnybody? 
You could do it with something like a Python script but are you asking for a batch file to do it?  What's a Baruch?  Might be a way in batch but it would be complicated.

Code: [Select]import os
import string

path = r'.'

for name in os.listdir(path):
   if os.path.isfile(os.path.JOIN(path, name)):
      if string.find(name, ' ') > 0 :
         fnm = name.split(' ')
         fname = '_'.join(fnm)
         os.rename(name, fname)
Baruch?
Not sure what that was. I have lost my eye teeth, do I can not see what I say.

Thanks for the Python script. I will add that to my collection.
Very simple in batch.

Code: [Select]echo off
setlocal enabledelayedexpansion
for /f "delims=" %%A in ('dir /b ^| find " "') do (
set oldname=%%A
set newname=!oldname: =_!
echo Renaming "!oldname!" to "!newname!"
ren "!oldname!" "!newname!"
)
echo Done
Pause

1104.

Solve : batch file to run vbscript in all subfolders?

Answer»

Hello,

I have been trying for days to create a batch file that will run a vbscript (dirlist.vbs) in every subdirectory and sub subdirectory of the parent directory. Is this even possible. I have found some examples that come close to what I am looking for through searching, but I can't make sense of them.

Any help would be greatly appreciated.


Never mind I got it worked out. For ANYONE looking for this:

CODE: [Select]
echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for EXAMPLE:
for %%f in (*.vbs) do cscript %%f
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /B

Well your code is still not setup correctly.

If all your vbscript does is ITERATE a directory listing you can easily do that a couple of ways with native batch script.

1105.

Solve : Copy or move wildcard foloders up to root.?

Answer»

On my PC I have downloaded a bunch of MP3 files during the past year. Sad to say, I am a POOR ORGANIZER. I don't always save the files in the save place or move them to the same place. I forget things.

The folders always have this pattern:

Code: [Select]w*2016????.mp3
Yes, that is for a folder. Yes, the folders have MP3 files.

My problem is to find the 12 folders and put them in one place. After that,I might delete the duplicates. Yes, I made duplicates when I could not remember where I put something.
This should be easy, I can not remember how to move a folder to a toot potion when it could be anywhere in the tree  of a volume.
Hondo you dot hat?
In brief, I want to find the folders that MATCH pattern and move them to the roof the volume. If a folder of the same name is already in the root, skip and do thenext thing..
Later I will delete the duplicates.
Thanks for reading this.   

 For the umpteenth time - if you are going to use speech to text, PROOFREAD YOUR POSTS. You're asking for help and making it difficult for anyone to understand what you are asking.OK, Try again. Simple code below:

Code: [Select]XCOPY /S xw*2016????.mp3 J:The above will copy all folders taht match to the J: drive and include the contents of the folders.
But some folders will still be inside other folders. I need all of the matching folders to be now at the top level. How else can I say it? 

Quote

The above will copy all folders taht match to the J: drive and include the contents of the folders.
But some folders will still be inside other folders. I need all of the matching folders to be now at the top level. How else can I say it?

Reading this, I am thinking your looking to Collapse the tree then so if you had the following:

Code: [Select]J:\data\1
J:\data\2
J:\data\3\4\5\6
That you would end up with:

Code: [Select]J:\1
J:\2
J:\3
J:\4
J:\5
J:\6
?

First of all I am pretty SURE it wouldnt be able to be all done on same drive due to cyclic error issue. All data would need to be moved elsewhere and then brought back to J: I believe. Drawing a blank on best method to collapse the tree. Its really easy to just grab all files and throw them into root of J:, but if you have files with same file names that will be a problem.

You only want it to be folders 1 level deep then as I showed above or am i not getting what your trying to do?

1106.

Solve : Can't set variable in for loop even when setlocal enabledelayedexpansion is on?

Answer»

Okay I have this script which uses a for loop to search through all batch files on the computer, I want to disable them by turning them Into a text file. However I  need to modify a variable but it will not set.

Here is the script

for %%A in ("%CD%") do set topfolder=%%~DA\
setlocal enabledelayedexpansion
for /l %%x in (1,0,2) do (
for %%A in (*.bat) do echo "%%~DPNXA"
for /r %%X in (*.bat) do echo "%%X"
CD..
if "!CD!"=="%TOPFOLDER%" call :end )
:end

What I'm trying to do is set this variable

for %%A in ("%CD%") do set topfolder=%%~DA\
setlocal enabledelayedexpansion
for /l %%x in (1,0,2) do (
for %%A in (*.bat) do set "file1=%%~DPNXA"
for /r %%X in (*.bat) do set "file2=%%X"
Echo !file1!
Echo !file2!
Pause
CD..
if "!CD!"=="%TOPFOLDER%" call :end )
:end

For some reason I just can't get the value "℅℅~DPNXA" To equal "!file1!" And I can't get "%%X" to equal to "!file2!", I want to do this so a can change them to something like this
"!file1:~0,-4!.txt".FIRST of all,doing nested FOR loops is way too hard for many of us.
Is there a good reason for using nested loops?
Have you tried it with out loops?

well i really haven't found any difficulty until now, figured out just about everything so far except this one issue, i was trying to avoid spaghetti code mainlyand yes i have tried without the for loop

the NON for loop version looks like this.

echo off
for %%A in ("%cd%") do set topfolder=%%~dA\
:start
for %%A in (*.bat) do set "file1=%%~dpnxA"
for /r %%X in (*.bat) do set "file2=%%X"
echo "%file1:~0,-4%.txt"
echo "%file2:~0,-4%.txt"
pause
if "%cd%"=="%topfolder%" goto root
cd..
goto start
:root
It sets variables for me, or not, depending on WHETHER there are any files that satisfy the filespec.

I can see some traps lurking...

I modified the script to provide some debug information (you should be doing this!)

Script is: E:\plex\data\Plex Media Server\test\test.bat

Script:

echo off
for %%A in ("%cd%") do set topfolder=%%~dA\
:start
echo CD="%cd%"
for %%A in (*.bat) do set "file1=%%~dpnxA"
for /r %%X in (*.bat) do set "file2=%%X"
echo "%file1:~0,-4%.txt"
echo "%file2:~0,-4%.txt"
pause
if "%cd%"=="%topfolder%" goto root
cd..
goto start
:root
echo Finished
Pause

Output:

CD="E:\plex\data\Plex Media Server\test"
"E:\plex\data\Plex Media Server\test\test.txt"
"E:\plex\data\Plex Media Server\test\test.txt"
PRESS any key to continue . . .
CD="E:\plex\data\Plex Media Server"
"E:\plex\data\Plex Media Server\test\test.txt"
"E:\plex\data\Plex Media Server\test\test.txt"
Press any key to continue . . .
CD="E:\plex\data"
"E:\plex\data\Plex Media Server\test\test.txt"
"E:\plex\data\Plex Media Server\test\test.txt"
Press any key to continue . . .
CD="E:\plex"
"E:\plex\data\Plex Media Server\test\test.txt"
"E:\plex\data\Plex Media Server\test\test.txt"
Press any key to continue . . .
CD="E:\"
"E:\plex\data\Plex Media Server\test\test.txt"
"E:\plex\data\Plex Media Server\test\test.txt"
Press any key to continue . . .
Finished
Press any key to continue . . .Your loop one gives values too...

Again, a couple of mods

E:\plex\data\Plex Media Server\test\test2.bat

echo off
setlocal enabledelayedexpansion
for %%A in ("%CD%") do set topfolder=%%~DA\
for /l %%x in (1,0,2) do (
for %%A in (*.bat) do set "file1=%%~DPNXA"
for /r %%X in (*.bat) do set "file2=%%X"
Echo !file1!
Echo !file2!
Pause
CD..
if "!CD!"=="%TOPFOLDER%" call :end
)
:end
Echo Finished
Pause


Output

E:\plex\data\Plex Media Server\test\test2.bat
E:\plex\data\Plex Media Server\test\test2.bat
Press any key to continue . . .
E:\plex\data\Plex Media Server\test\test2.bat
E:\plex\data\Plex Media Server\test\test2.bat
Press any key to continue . . .
E:\plex\data\Plex Media Server\test\test2.bat
E:\plex\data\Plex Media Server\test\test2.bat
Press any key to continue . . .
E:\plex\data\Plex Media Server\test\test2.bat
E:\plex\data\Plex Media Server\test\test2.bat
Press any key to continue . . .
Finished
Press any key to continue . . .
 

I'd be in interested to know what you think these scripts are going to do...


Thank you, I'll have to check it out tomorrow, I'll SWING back back and tell you if it worked for me. Quote from: zask on February 02, 2017, 02:56:54 PM

Thank you, I'll have to check it out tomorrow, I'll swing back back and tell you if it worked for me.
I think the issue I was having was not being able to see the values within the loop, because when I typed echo "%%~DpnxA"  and echo "%%X", nothing appeared except "", so it made it difficult to make debug notes within the script.Is there a way to make it ignore file paths that don't satisfy or end with the .bat extension before its path is set to the variable and modified to an .txt extension? I know everything isnt possible in batch but thank you anyway for the help. Quote from: zask on February 02, 2017, 03:24:07 PM
when I typed echo "%%~DpnxA"  and echo "%%X",
They appear for me. Where and when were you "typing" these things?

     When I'm trying to put it in !file1! & !file2! Running inside the infinite for loop, it just didn't appear for some reason  Quote from: zask on February 02, 2017, 06:07:42 PM
When I'm trying to put it in !file1! & !file2! Running inside the infinite for loop, it just didn't appear for some reason, I don't know why but I'll try to figure it out.
What do you mean I would be interested to know what they are going to do? Quote from: zask on February 02, 2017, 06:33:14 PM
What do you mean you would be interested to know what they are going to do? I'm trying to mimic the assoc command without actually setting every file's extension to a different extension permanently until you change it back, well it would change it like that, but it wouldn't permanently associate every extension for every file after that. If sure you understand what I mean if you have ever used the assoc command.
1107.

Solve : batch file to convert text file into excel?

Answer»

Hello Guys,
Very new to this forum
I need to have a batch file program  which converts text file into Excel format
as an example the contents will have 3 lines as below:
1|0|32|1|1|2|0|0|1|0|0|2222|0|0|0|0|20170130151125|20170130151210|
2|0|32|1|1|2|1|1|1|2222|1000|2222|0|0||0|20170130151125|20170130151210|
10000|0|32|1|1|2|NULL|0|0|0|0|0|0|0|0|0|20170130151125|20170130151210|

the 2nd line needs to be address importantly for further processing.




Thanks
Rajesh
If I understand your question correctly, you don't need any form of batch file.  You can use the DATA import function of Excel to import the data.  You will need to setup the DELIMITER as the '|' character since it is used in your text file to separate the data values.

What version of Excel are you using?Batch FILES cannot read or WRITE excel files.  If you need to read or write excel files then use  Vbscript, Jscript or Powershell. Quote from: Squashman on February 01, 2017, 07:24:09 AM

Batch files cannot read or write excel files.  If you need to read or write excel files then use  Vbscript, Jscript or Powershell.
Your logic is backward.  He does not need a batch file to read or write Excel files.  He needs to know how to import data into Excel.  Quote from: soybean on February 01, 2017, 08:39:53 AM
Your logic is backward.  He does not need a batch file to read or write Excel files.  He needs to know how to import data into Excel.
No. I import (write) text files into excel all the time with Vbscript.  There is nothing illogical about it. Quote from: Squashman on February 01, 2017, 08:56:15 AM
I import (write) text files into excel all the time with Vbscript.  There is nothing illogical about it.
Absolutely.
1108.

Solve : Call .bat and go to label??

Answer»

I googled it, thought I found a solution but it doesn't seem to work. I think I saw a thread on this a while back but I can't find it (the search NEVER seems to work for me on the forum here for some reason, I get "no results" no matter what I search for). I'm USING Win7 if that makes a difference. I found something that said extensions had to be enabled for this to work then checked my registry according to another site and determined they are enabled. I also tried setlocal enableextensions at the head of test.bat, that didn't work either.

I made these two test batch files:

test.bat
Code: [Select]echo off

cls
echo.
echo.
echo.
echo     Make a selection
echo.
echo.
echo     [1] selection 1
echo     [2] selection 2
echo     [3] exit
echo.
set /p selection=
if %selection%==1 call test1.bat one
if %selection%==2 call test1.bat two
if %selection%==3 exit


test1.bat
Code: [Select]echo off
echo.
echo.
echo.
echo this shouldn't ever show

:one
echo.
echo.
echo.
echo this is selection 1
pause
call test.bat

:two
echo.
echo.
echo.
echo this is selection 2
pause
call test.bat


"this shouldn't ever show" shows every time and if I choose selection 2 it shows "this shouldn't ever show" and then tells me I'm seeing the stuff under label :one rather than :two indicating that my call command is merely calling test1.bat and ignoring the labels entirely. I've tried call test1.bat :one (note the colon) and I tried setting "one" as a variable (set selection1=one) and then call test1.bat %selection1%, no luck either way (not that I was really expecting a different result, but...). What am I doing WRONG? If you copy those and run test.bat do you get the same result?

Seems like it should be so simple!

JimLabel names are only valid inside the script. You can't just add the label name after the batch name and expect the script to know what you mean. If you want to pass the label name as a single parameter from the command line (or another script), you could insert:

goto %1

after the echo off line.

Doing it this way means you must always pass a valid label name or the script will halt with an error.

Or you can do IF tests, e.g.

if "%1"=="one" goto one
if "%1"=="two" goto two
...etc
(you need a final goto to catch a wrong or missing label)


By the way, looking at your example script:

Code: [Select]:one
pause
call test.bat

:two
echo.
You do realise that this code will always go to :two after test.bat has finished? After a label section, you need to explicitly goto (somewhere) otherwise execution will continue at the next code line, skipping any labels, which may not be what you wanted it to do. I really appreciate the help Salmon Trout, I didn't know about %1. That's perfect, did the trick!

Quote from: Salmon Trout on January 28, 2017, 04:38:44 PM

You do realise that this code will always go to :two after test.bat has finished?

I'd forgotten about that, but as it turned out it worked OK with this particular example since test.bat would either call test1.bat again or exit depending on the selection chosen. I can see the error of my ways though if set /p didn't pause test.bat waiting for user input it would finish and then go back to test1.bat :two. Here's what I came up with, I guess GOING to :EOF after the pause would terminate test1.bat so it doesn't return after test.bat finishes (and :two doesn't need it because we're at EOF when it returns to test.bat anyway)?

test1.bat
Code: [Select]echo off

goto %1

echo.
echo.
echo.
echo this shouldn't ever show

:one
echo.
echo.
echo.
echo this is selection 1
pause
::call test.bat
goto :EOF

:two
echo.
echo.
echo.
echo this is selection 2
pause


That seems to do what I wanted to do anyway, still working on catching wrong or missing labels.

Again, I appreciate the help.

Jim Quote from: JRobinson on January 29, 2017, 12:02:15 AM
Here's what I came up with, I guess going to :EOF after the pause would terminate test1.bat so it doesn't return after test.bat finishes (and :two doesn't need it because we're at EOF when it returns to test.bat anyway)?
Perfect! Sometimes with labels instead of the implicit :eof I put a final one called :end or whatever and have something like this

:end
echo Script finished
pause


1109.

Solve : Batch/Multi rename only files with a specific range?

Answer»

Hello, i hope someone can help me with this.

i have a bunch of consecutive  files
sometimes 10 files sometimes 22 files - it doesn't MATTER how MUCH
 e.g
001.xxx
002.xxx
003.xxx
004.xxx
...
i want to write a Bach file that will duplicate all files except the first and last and will rename them Consecutively to the last file
so for the e.g above it will look like this:

001.xxx
002.xxx
003.xxx
004.xxx
 005.xxx
 006.xxx

file 003.xxx was duplicated+renamed to 005.xxx
and file 002.xxx was duplicated+renamed to 006.xxx
first file 001.xxx and last files  in this case it was 004.xxx didn't play in this command
 i did WROTE this command:

copy 003.xxx 005.xxx
copy 002.xxx 006.xxx

but this command is only working if i am starting with 4 files
the PROBLEM is the amount of files i am starting with is different each time
i need your help to write something that will apply only on the 'between' files no matter how much of them

Thank youSo use a FOR /F command to parse the output of the DIR command.  Use the options with the DIR command to sort the file alphabetically and then in REVERSE.

1110.

Solve : Creating a batch file to run RDP and connect?

Answer»

Hi, I am a complete novice with zero experience.

I have daily tasks at work which require me to RDP to servers to check logs etc and was hoping I could create a batch file to launch on startup to save myself a bit of time.

Any help would be greatly appreciated.

So far all I have DONE is copy scripts I have found online but I'm struggling to find something suitable for my needs in this instance.  I have read some of the threads in this forum on similar requests but am baffled :/


Thanks

AdrianSo far I have got this far..

start /d "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories" mstsc.exe

I'm such a n00b its almost embarrassing  I don't RDP anywhere - what did you want to automate?

What procedure do you use to RDP?Hi, did I not reply to your question above?

Ideally I want to automate logon to an exchange server and run services.msc or test-servicehealth.  This check is one of my daily checks.http://windows.microsoft.com/en-AU/windows-vista/Use-command-line-parameters-with-Remote-Desktop-Connection

You can automate the connection here.

You might like to use PSEXEC to connect remotely and execute programs and get info, but not if you need GUI access.Not really sure what I need to add to make this work, there are no examples :/ I get further with what I've written already.  I need to automate the launch - connection - fill password field - connect.

I dont know if this is even possible.

Thanks for the link though. After further investigation I think a batch file maybe inappropriate for my needs, thoughts?The link shows that you need a connection file, and that will allow you to connect to the remote server with few keystrokes.

You create/edit the connection file and write the batch file, call it R.BAT and put it in c:\Windows
Then press Windows + R, type R and press enter.  You should be connected.

The way I read it the link shows that with a connection file all you need is this:

Code: [Select]echo off
mstsc "%userprofile%\desktop\server1.rdp"


where you create the server1.rdp on your desktop.  You may be able to just double click the RDP file if the associations work.
Well ive stumbled accross this online,

mstsc /v: "IPADDRESSHERE" /w:640 /h:480

Which gets me as far as putting my password in, any ideas for another line to add password and HIT ok a few times?Right I just need a command to fill the password field then im there.  Anyone help out?Even if you do get your SCRIPT working, you will save yourself a huge amount of effort using this if you keep having to log into different (windows) servers - the Remote Desktop Connection Manager
http://www.microsoft.com/en-us/download/details.aspx?id=21101PowerShell can create that script. Will create a temp connection to the target machine.
set-location \\targetmachine\c$Did you try dropping down to "cmd" and typing "mstsc /?"  This will give you all of the commands that remote desktop will use/require.
I use batch files in the same way you do with a choice command to go through the remote serversSOLUTION:
Best way to go about this is open mstsc enter all your connection details then click save as, save to the desktop and your done. 

However if you wish to run mstsc as an ADMINISTRATOR or for any other elevated commands create a notepad and enter:   mstsc /v:rdp.mycompany.com /console /admin
save as RDP.batThey left 1 1/2 Years AGO...

1111.

Solve : Batch file "IF" error "GoTo" EOF commandline?

Answer»

Hi, I didn't know this forum existed until today, how awesome!!
I'm MAKING a vb6 program which creates and shell executes a batch file.
The batch file has four commands, three of which are to a game engine required to compile maps.
The fourth command is to a pop-up exe file I've created to alert the user when the whole process has completed.

It all works great except when one of the three map compile processes hit a major compile error and the CMD console (DOS box) closes before processing any of the remaining commands.

I would like to place "If" and "GoTo" conditions to each of the three process commands so that it will go through all four commands normally but also GoTo the fourth command on error.
Something like...
If commandline1 errs goto COMMANDLINE 4
If commandline2 errs goto commandline 4
If commandline3 errs goto commandline 4
commandline 4 (sends pop-up alert)

Pure and simple, please. I have searched for this all day and everything I have found has gone clear over my head.
I don't need "If EXISTS", I know they do (besides I can call that in vb), but most search results I have read on batch file "If"s are "If Exists".

I do apologize if this is in the wrong forum and understand if it is moved.
I just saw "DOS" and thought DOS command console. It's actually a Windows/DOS topic. A little from column A, a little from column B.

Go easy with the guru lingo, I'm old, a long way from the good ol' DOS days and it's my first time here.
Thank you. Quote from: AccadaccA on January 07, 2017, 03:23:03 AM

The batch file has four commands, three of which are to a game engine required to compile maps.
Since we are not telepaths, the actual code would make the task of deciding if we can help a lot easier. You can clean up personal references or sensitive stuff.
Sorry, I didn't think that the path and  filename specifics would make a difference.
Code: [Select]"C:\MOHAAT~1\Q3map.exe" -v -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox
"C:\MOHAAT~1\Q3map.exe" -vis -fast -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox
"C:\MOHAAT~1\MOHlight.exe" -fast -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox
"C:\Program Files (x86)\Microsoft VISUAL Studio\VB98\My Projects\Map Mate\041\done.exe"

As I said, the batch works well except when error occurs with either stage of the compile (first three command lines)You could check for the exit code from the apps you are running, Q3map.exe and MOHlight.exe, assuming that they give a nonzero exit code when the errors of which you speak occur.

Do these programs give console output?

You could try something like this using the && (zero ERRORLEVEL) and || (nonzero errorlevel) tests

Code: [Select]Echo Starting sequence...
echo Starting task 1 of 3
"C:\MOHAAT~1\Q3map.exe" -v -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox && (echo OK) || (goto error)
echo starting task 2 of 3
"C:\MOHAAT~1\Q3map.exe" -vis -fast -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox && (echo OK) || (goto error)
echo Starting task 3 of 3
"C:\MOHAAT~1\MOHlight.exe" -fast -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox && && (echo OK) || (goto error)
goto done
:error
echo ERROR
:done
"C:\Program Files (x86)\Microsoft Visual Studio\VB98\My Projects\Map Mate\041\done.exe"Correction (accidentally doubled the &&)

Code: [Select]echo Starting task 3 of 3
"C:\MOHAAT~1\MOHlight.exe" -fast -gamedir C:\Games\MOHAA C:\Games\MOHAA\main\maps\skybox && (echo OK) || (goto error)Sorry for not getting back to this sooner, life got in the way.

Thank  you, I will give that a try.


edit: Sorry I skipped this..
Quote from: Salmon Trout on January 07, 2017, 07:20:39 AM
.........
Do these programs give console output?
Yes, they do, for several minutes.Whoohoo!!

It worked perfectly.  Thank you, Salmon Trout.

Sorry, I don't have any erroneous maps so I had to ask around for some so I could test the bat. lolI can't see how to mark the thread as "Resolved".
1112.

Solve : GTR and LSS seem to fail for large sizes?

Answer»

Was trying to determine which ISOs are BluRay and which are DVD and I picked 9gb as the size cutoff.  %~z1 gave the correct size but GTR failed to calculate properly.  Maybe I did something wrong or perhaps there is another way to differentiate the two types.

echo %1 %~z1
ECHO OFF
SET SIZELIMIT=9000000000
SET FILESIZE=%~z1

IF %FILESIZE% GTR %SIZELIMIT% GOTO No

ECHO DVD
PAUSE
GOTO :EOF

:No
ECHO BluRay
PAUSE
GOTO :EOF

Thanks for looking.Correct.  Because batch files can only handle 32bit Integers.Change your IF comparison to use quotes.

Code: [Select]IF "%FILESIZE%" GTR "%SIZELIMIT%" Goto No ECHO OFF
echo Wscript.echo eval(WScript.Arguments(0)) > evaluate.vbs
echo %1 %~z1
SET SIZELIMIT=9000000000
SET FILESIZE=%~z1
for /f "delims=" %%A in ('cscript evaluate.vbs "%filesize% > %sizelimit%"') do set result=%%A
If %result% equ -1 goto no
ECHO DVD
PAUSE
GOTO :EOF
:No
ECHO BluRay
PAUSE
GOTO :EOF
The suggestion to use quotes did not work.  Possibly only the first letter is checked.  However, Salmon's evaluate.vbs worked fine.  Sizeof or strlen would have worked OK if they existed.Well I tested it a few times with quotes and it worked. No it does not just compare the first character.Strange - I tested it on both the Win10 command prompt and the Micro$oft VS 14 one and it appears only to check the first character.   Are you using the power shell or some other extension?

You know you can copy and paste text from the cmd window.  Wouldn't that be a lot EASIER then posting a SCREEN shot?

Quote from: BeemerBiker on February 14, 2017, 07:12:39 AM
Strange - I tested it on both the Win10 command prompt and the Micro$oft VS 14
You realize there is no difference between the two?  You are just in a different directory.As Squashman stated, it doesn't only compare the first character.

The confusion is in expecting a numeric comparison. The use of quotation marks makes it no longer a numeric comparison, instead, it is comparing the two values as strings.

Code: [Select]if "2" LSS "10" (echo lower) else (echo higher)
outputs "higher", becasue it is comparing the string "2" to the string "10" alphanumerically.

The "solution" is to have it use leading zeroes:

Code: [Select]if "02" lss "10" (echo lower) else (echo higher)

outputs "lower".

using VBScript via evaluate.vbs tends to be the better alternative if you want to exceed the rather basic math capabilities of batch.
Quote from: BeemerBiker on February 13, 2017, 04:30:14 PM
Sizeof or strlen would have worked OK if they existed.
echo off
set mystring=9000000000
call :strlen %mystring%
echo string length %slen%
goto end

:strlen
set slen=0
set tempstring=%1
:loop
set tempstring=%tempstring:~0,-1%
set /a slen+=1
if "%tempstring%"=="" goto :eof
goto loop

:end
echo done
pause
1113.

Solve : command prompt to samsung galaxy j2 model SM-J200F?

Answer»

Greetings,
Windows 7, my computer show the device as "Galaxy J2". How do i access this device from the command prompt? Thanks.Why do you need to access it from command prompt? What are you trying to do so we can better ASSIST if its even possible or not?Thank you, I want to run eg. dir/s to analysis the files on the mobile phone.You can't. At least, not easily.

Phones do not connect as Mass Storage devices. They connect, INSTEAD, via the Media Transfer Protocol. They don't appear as storage drives, but instead are interfaced via a different protocol. This is out of reach of the Command Prompt in general.

The only way to get this, I think, would be to root the phone and install some sort of software designed to allow the phone to be exposed as a Mass storage device instead of an MTP device.

Maybe it can be manipulated directly via Powershell?You can install an SSH or Telnet server on an Android phone and OPEN a console to it.
Thank you, I have installed telnetd on mobile. Please EXPLAIN to me the steps how to use it. Thank you.

1114.

Solve : Find_Suspicious_SVCHOST_Paths.bat?

Answer»

Hi 
I made this batch script in order to identify if there is a virus or trojan with svchost.exe name

  • svchost.exe is good and functions like a container for relevant services
  • svchost.exe is only a virus if it’s living outside C:\Windows\System32
Code: [Select]echo off
REM First release on 01/03/2017 04:45
REM Updated on 07/03/2017 04:05
Set "ProcessName=SVCHOST"
Set "Tmp_Services=%Tmp%\%~n0.txt"
If Exist "%Tmp_Services%" Del "%Tmp_Services%"
Set "ProcessLog=%Tmp%\%ProcessName%.log"
If Exist "%ProcessLog%" Del "%ProcessLog%"
Set "Legits_Services_SVCHOST=%~dp0Legits_Services_%ProcessName%.txt"
Set "Legit_Location=%windir%\system32\svchost.exe"
Set "LogFile=%~dp0%ProcessName%_ProcessList.txt"
Set "Suspicious_LogFile=%~dp0%ComputerName%_%ProcessName%_Suspicious_Paths.txt"
Title Finding all instances and paths of "%ProcessName%" by Hackoo 2017
If Exist "%LogFile%" Del "%LogFile%"
Set /A Counter=0
setlocal enableDelayedExpansion
for /F "skip=1" %%a in ('WMIC Path win32_process where "name like '%%%ProcessName%%%'" get commandline') do (
for /F "delims=" %%b in ("%%a") do (
Color 0A
set /A Counter+=1
set "p=%%b"
for /f %%f in ('echo !p! ^|Findstr /LI "%Legit_Location%"') do (
echo [!Counter!] : !p!
)
( echo "!p!" )>>"%LogFile%"
)
)

Powershell.exe Get-WmiObject Win32_Process ^| select ProcessID,ProcessName,Handle,commandline,ExecutablePath ^| Out-File -Append "%ProcessLog%" -Encoding ascii
TYPE "%ProcessLog%" | find /i "%Legit_Location%" > "%Tmp_Services%"

(
echo(
echo Those are legitimes services of "%ProcessName%.exe"
Tasklist /SVC /FO TABLE /FI "IMAGENAME eq %ProcessName%.exe"
)>con

(
echo(
echo Those are legitimes services of "%ProcessName%.exe"
Tasklist /SVC /FO TABLE /FI "IMAGENAME eq %ProcessName%.exe"
)>> "%Tmp_Services%"
CMD /U /C Type "%Tmp_Services%" > "%Legits_Services_SVCHOST%"
echo(
Echo All instances of "%ProcessName%" in this path "%Legit_Location%" are legitimes services
echo(
echo Hit any KEY to look for a SUSPICIOUS "%ProcessName%" paths
Findstr /LVI "%Legit_Location%" "%LogFile%" > "%Suspicious_LogFile%"
PAUSE>nul
Start "" "%Suspicious_LogFile%"
Start "" "%Legits_Services_SVCHOST%" & exit
::*********************************************************************************************Do you have a question? Quote from: Squashman on March 07, 2017, 07:29:49 AM
Do you have a question?
Yes ! I have just tested this script under Windows 7 (32 bits) !
I wonder if there is another legit location of svchost.exe on (64 bits machines) ?
for example should i check it on sysWOW64 location or not ?
Thank you !
1115.

Solve : search for mutiple txt files and copy file name and path into one txt file?

Answer»

How can I search for multiple  txt files with the partly same name under multiple subfolders and COPY that filename and path to that file into one txt file.
like
d:\users\mike\log\logfileL22102017.txt
d:\users\john\log\logfileH12022017.txt
d:\users\claire\log\logfileH03042017.txt
d:\users\billy\log\logfileL10112017.txt

all that files logfile*.txt in new file copied_logfiles.txt
copied_logfiles.txt will be in folder d:\users\copied_logfiles.txt also batch which will create that file.

copied_logfiles.txt will look like this when I open.
d:\users\mike\log\--->L.txt
d:\users\john\log\--->H.txt
d:\users\claire\log\--->H.txt
d:\users\billy\log\--->L.txt


I need a list of files in one txt file if users logfile is marked with H or L so I need to CHECK users folder and which txt file is currently in L or H.
Now I need to check every user subfolder and check if there is logfileL22102017.txt  with L in it or logfileH03042017.txt with H in it.
If it is more than 5 hours L than I need to do something to get for user to have  logfileH03042017.txt with H in it.

Can someone help me with batch?
You can use wildcards in a directory command.

For example, lets say you are in the d:\users directory and wanted to find all files beginning with logfileh that were text files. You could type the following command.

dir logfileh*.txt /s

The "/s" will DISPLAY RESULTS for all subdirectories from the d:\users directory.

If you wanted the results to go to a text file you could use the append symbol to append the results to a text file. Below is an example of the same command.

dir logfileh*.txt /s > c:\users\copied_logfiles.txt

Like any command line command this command can be added to any batch file.Hi 
There is another command named  WHERE  : To locate and display files in a directory tree
Quote

WHERE (Windows 2003 + )

Locate and display files in a directory tree.

The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in the PATH.

Syntax
      WHERE [/r Dir] [/q] [/f] [/t] Pattern ...

      WHERE [/q] [/f] [/t] [$ENV:Pattern

key
   /r      A RECURSIVE search, starting with the specified Dir directory.

   /q      Don’t display the files but return either an exit code of 0 for success
           or 1 for failure.

   /f      Display the output file name in quotation marks.

   /t      Display the size, time stamp, and date stamp of the file.

  pattern  The Drive\Directory\file, or set of files to be found.
           you can use wildcard characters ( ? * ) and UNC paths.

   ENV     Path to search where ENV is an existing environment variable containing one or more paths.

By default, WHERE searches the current directory and the paths specified in the PATH environment variable. Optional search paths (in pattern) should not be used in conjunction with /r Dir.
I know but I don't know how to put it in batch for my caseI have managed to make a list with paths but cant make it to write at the end of path if file is logH.txt or logL.txt
Code: [Select]for /f  "tokens=*" %a in ('dir .\log /B /S) do echo %~fa %~za >> d:\users\drivers\mike\testfolder\List.txtthis one says can not find file
Code: [Select]for /f  "tokens=*" %a in ('dir .\new /s /b /A-D "*.txt"') do echo %~fa %~za >> d:\users\drivers\mike\testfolder\List.txtHi 
You can give a try for this batch file : Search_LogFiles.bat
Code: [Select]echo off
Title Searching files . . .
Color 9E & Mode con cols=75 lines=3
set "Master_Folder=C:\users"
set "Pattern=logfile*.txt"
set "LogSearch=%~dpn0.txt"
echo(
echo      Please wait ... Searching "%Pattern%" files is in progress ...
Where /R "%Master_Folder%" "%Pattern%" /F >"%LogSearch%" 2>&1
start "" "%LogSearch%"I have one problem here.
loghi*.txt files are also in folder logfiles and in its subfolder new it is only one.
And I need only file from subfolder new, this script finds also fles in folder logfiles.

d:\users\john\logfiles\logfileH12022017.txt

this file I am looking for to write in txt
d:\users\john\logfiles\new\logfileH12022017.txt

Quote from: Blisk on May 23, 2017, 12:07:37 AM
I have one problem here.
loghi*.txt files are also in folder logfiles and in its subfolder new it is only one.
And I need only file from subfolder new, this script finds also fles in folder logfiles.

d:\users\john\logfiles\logfileH12022017.txt

this file I am looking for to write in txt
d:\users\john\logfiles\new\logfileH12022017.txt

In this case you can try like that if i understood what you mean ?
Code: [Select]echo off
Title Searching files . . .
Color 9E & Mode con cols=75 lines=3
set "Master_Folder=C:\users"
set "Pattern=logfile*.txt"
set "LogSearch=%~dpn0.txt"
echo(
echo        Please wait ... Searching "%Pattern%" files is in progress ...
Where /R "%Master_Folder%" "%Pattern%" /F >"%LogSearch%" 2>&1
Type "%LogSearch%" | find /I "new" > NewLog.txt
start "" NewLog.txtI named that batch test.bat and it also creates test.txt where all logfile*.txt are in, from \logfiles folder too which is wrong.
But at the same time it opens notepad named NewLog.txt where is result which I want, from folder \new

How to do this to get results saved in NewLog.txt and there is no test.txt created and doesn't open notepad.exe but save directly to NewLog.txt file.

And is it possible to get result in txt file from this logfileH12022017.txt to this logfileH?

Hot Quote from: Blisk on May 23, 2017, 02:37:06 AM
I named that batch test.bat and it also creates test.txt where all logfile*.txt are in, from \logfiles folder too which is wrong.
But at the same time it opens notepad named NewLog.txt where is result which I want, from folder \new

How to do this to get results saved in NewLog.txt and there is no test.txt created and doesn't open notepad.exe but save directly to NewLog.txt file.

And is it possible to get result in txt file from this logfileH12022017.txt to this logfileH?

Hot
Did you mean something like that ?
Code: [Select]echo off
Title Searching files . . .
Color 9E & Mode con cols=75 lines=3
set "Master_Folder=C:\users"
set "Pattern=logfile*.txt"
Rem Name it as you want
set "LogSearch=TextFile_As_You_want_here.txt"
echo(
echo        Please wait ... Searching "%Pattern%" files is in progress ...
Where /R "%Master_Folder%" "%Pattern%" /F >"%LogSearch%" 2>&1
REM We filter our search into file named NewLog.txt
Type "%LogSearch%" | find /I "new" > NewLog.txt
Rem We delete the "%LogSearch%"
If exist "%LogSearch%" Del "%LogSearch%"Thank you this is what I want.
1116.

Solve : [Batch] Extracting targets from shortcuts Links?

Answer»

Hi 
I have READ this topic ==> How to read target of .lnk file with COMMAND line
So; i want to share my solution in new topic instead of digging this later
Extract_Target_Link.bat
Code: [Select]echo off
Title Extracting targets files from links by Hackoo 2017
Mode con cols=50 lines=3 & color 9E
Set "Log=%~dp0TARGET_LINK_PATHS.txt"
If exist "%Log%" Del "%Log%"
Set "Folders=%UserProfile%\Desktop %Public%\Desktop %AllUsersprofile%"
For %%F in (%Folders%) Do (
Cls
Echo *****************************************************************
Echo "%%F"
(echo; & echo        Scanning "%%F" ...)>CON
Echo *****************************************************************
Echo(
For /f "delims=" %%L in ('Dir /b /s "%%F\*.lnk"') do (
echo "%%L" & Call:ExtractTarget "%%L"
echo  --------------------------------------------------------
)
)>>"%Log%"
Start "" "%Log%"
Exit
::*************************************************************************
:ExtractTarget <Link>
(
echo set Ws = CreateObject("WScript.Shell"^)
echo set Lnk = Ws.Createshortcut(WScript.Arguments(0^)^)
echo WScript.echo Chr(34^) ^& Lnk.TargetPath ^& Chr(34^)
)>"%Tmp%\Tmp.vbs"
cscript //nologo "%Tmp%\Tmp.vbs" "%~1"
Del "%Tmp%\Tmp.vbs"
Exit /b
::*************************************************************************Hi 
This the updated VERSION : I added the *.url extension to be scanned too   
Code: [Select]echo off
Title Extracting target from shortcut (*.url) and (*.lnk) by Hackoo 2017
Mode con cols=62 lines=3 & color 9E
Set "Log=%~dp0TARGET_LINK_PATHS.txt"
Set "Links=url lnk"
If exist "%Log%" Del "%Log%"
Set "Folders=%UserProfile%\Desktop %Public%\Desktop %AllUsersprofile%"
For %%i in (%Links%) Do (
For %%F in (%Folders%) Do (
Cls
Echo *****************************************************************
Echo "%%F" for "*.%%i" Links
(echo. & echo     Scanning "%%F" for "*.%%i" Links ...)>CON
Echo *****************************************************************
Echo;
For /f "delims=" %%L in ('Dir /b /s "%%F\*.%%i"') do (
echo "%%L" & Call:ExtractTarget "%%L"
echo  --------------------------------------------------------
)
)
)>>"%Log%"
Start "" "%Log%"
Exit
::*************************************************************************
:ExtractTarget <Link>
(
echo set Ws = CreateObject("WScript.Shell"^)
echo set Lnk = Ws.Createshortcut(WScript.Arguments(0^)^)
echo WScript.echo Chr(34^) ^& Lnk.TargetPath ^& Chr(34^)
)>"%Tmp%\Tmp.vbs"
cscript //nologo "%Tmp%\Tmp.vbs" "%~1"
Del "%Tmp%\Tmp.vbs"
Exit /b
::*************************************************************************Why does it write the same TEMP vbs file EVERY time it needs to process a shortcut, and delete it again?
Quote from: Salmon Trout on February 08, 2017, 12:54:10 PM

Why does it write the same temp vbs file every time it needs to process a shortcut, and delete it again?
Thank you for your remark and i changed it to this code :
Code: [Select]echo off
Title Extracting target from shortcut (*.url) and (*.lnk) by Hackoo 2017
Mode con cols=62 lines=3 & color 9E
Set "Log=%~dp0TARGET_LINK_PATHS.txt"
Set "TmpVbs=%Tmp%\%~n0.vbs"
Set "Links=url lnk"
If exist "%Log%" Del "%Log%"
Set "Folders=%UserProfile%\Desktop %Public%\Desktop %AllUsersprofile%"
For %%i in (%Links%) Do (
For %%F in (%Folders%) Do (
Cls
Echo *****************************************************************
Echo "%%F" for "*.%%i" Links
(echo. & echo     Scanning "%%F" for "*.%%i" Links ...)>CON
Echo *****************************************************************
Echo;
For /f "delims=" %%L in ('Dir /b /s "%%F\*.%%i"') do (
echo "%%L" & Call:ExtractTarget "%%L"
echo  --------------------------------------------------------
)
)
)>>"%Log%"
Start "" "%Log%"
If Exist "%Tmpvbs%" Del "%Tmpvbs%"
Exit
::*************************************************************************
:ExtractTarget <Link>
(
echo set Ws = CreateObject("WScript.Shell"^)
echo set Lnk = Ws.Createshortcut(WScript.Arguments(0^)^)
echo WScript.echo Chr(34^) ^& Lnk.TargetPath ^& Chr(34^)
)>"%Tmpvbs%"
cscript //nologo "%Tmpvbs%" "%~1"
Exit /b
::*************************************************************************It still does it. Quote from: Salmon Trout on February 09, 2017, 03:50:36 AM
It still does it.
Ok
Can you provide me a better solution with code to optimize this later
Thank you !You wrote that code, didn't you? Just move the part that creates the vbscript out of the subroutine and put it at the start of the script.Ok  I think this is better 
Code: [Select]echo off
Title Extracting target from shortcut (*.url) and (*.lnk) by Hackoo 2017
Mode con cols=62 lines=3 & color 9E
Set "Log=%~dp0TARGET_LINK_PATHS.txt"
Set "TmpVbs=%Tmp%\%~n0.vbs"
::************************************************************************
(
echo set Ws = CreateObject("WScript.Shell"^)
echo set Lnk = Ws.Createshortcut(WScript.Arguments(0^)^)
echo WScript.echo Chr(34^) ^& Lnk.TargetPath ^& Chr(34^)
)>"%Tmpvbs%"
::************************************************************************
Set "Links=url lnk"
Set "Folders=%UserProfile%\Desktop %Public%\Desktop %AllUsersprofile%"
For %%i in (%Links%) Do (
For %%F in (%Folders%) Do (
Cls
Echo *****************************************************************
Echo "%%F" for "*.%%i" Links
(echo. & echo     Scanning "%%F" for "*.%%i" Links ...)>CON
Echo *****************************************************************
Echo;
For /f "delims=" %%L in ('Dir /b /s "%%F\*.%%i"') do (
echo "%%L" & Call:ExtractTarget "%%L"
echo  --------------------------------------------------------
)
)
)>>"%Log%"
Start "" "%Log%"
If Exist "%Tmpvbs%" Del "%Tmpvbs%"
Exit
::*************************************************************************
:ExtractTarget <Link>
cscript //nologo "%Tmpvbs%" "%~1"
Exit /b
::*************************************************************************
1117.

Solve : Help Im Stuck with Batch Variables in Loops?

Answer»

First of all here is my script.

echo off

FOR /F "tokens=2 delims==" %%a in ('WMIC NIC where "Manufacturer='Realtek' and PNPDeviceID like 'USB%%'" GET GUID /VALUE') DO ( SET GUID=%%a
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%GUID%" sValueName="EnableDHCP" uValue="1"
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%GUID%" sValueName="IPAddress" sValue=""
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%GUID%" sValueName="SubnetMask" sValue=""
)

all my commands work.. so to speak im struggeling with my variable. If i echo it, it returns the right value, if i change my variable with the actual value my COMMAND works and i can tell by the return value my commands are giving me that my loop works to. I tried different approaches but the clock is running late and im getting blinder by the hour so please help. You are inside a code block. You you need to enable delayed expansion and reference your variables with exclamation points instead of the percent symbol.  But there is no need for you to set the FOR variable to an environmental variable.  Just use the FOR variable in your commands.First of all thanks for replying... I tried that already I updated the script to show how i did it just in case i made an error.
it didnt work but thanks for trying though

echo off
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=2 delims==" %%a in ('WMIC NIC where "Manufacturer='Realtek' and PNPDeviceID like 'USB%%'" GET GUID /VALUE') DO (   
   SET GUID=%%a
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="EnableDHCP" uValue="1"
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="IPAddress" sValue=""
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="SubnetMask" sValue=""
)
ENDLOCAL
No clue.  When I use your code I get the correct output for my my Intel NIC.
Code: [Select]echo off
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=2 delims==" %%a in ('WMIC NIC where "Manufacturer='Intel'" GET GUID /VALUE') DO (
   SET GUID=%%a
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="EnableDHCP" uValue="1"
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="IPAddress" sValue=""
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\!GUID!" sValueName="SubnetMask" sValue=""
)
ENDLOCAL
pauseOutput
Code: [Select]WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{63C9BB9F-7582-43F7-8950-C524E83018B7}\" sValueName="EnableDHCP" uValue="1"
WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{63C9BB9F-7582-43F7-8950-C524E83018B7}" sValueName="IPAddress" sValue=""
WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{63C9BB9F-7582-43F7-8950-C524E83018B7}" sValueName="SubnetMask" sValue=""

But like I said earlier.  Why not just use the FOR variable directly.
Code: [Select]echo off
FOR /F "tokens=2 delims==" %%a in ('WMIC NIC where "Manufacturer='Realtek' and PNPDeviceID like 'USB%%'" GET GUID /VALUE') DO (   
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%%a" sValueName="EnableDHCP" uValue="1"
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%%a" sValueName="IPAddress" sValue=""
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%%a" sValueName="SubnetMask" sValue=""
)
HEY again thanks and sorry for my late reply.
I tried Both... If i setlocal enabledelayedexpansion i need to set a variable in order to change percentage to exclamation marks on my variables as far
as i know. I also tried to use the for variable directly, in that case i DONT need to enabledelayedexpansion and to set a variable. I like this approach better since it KEEPS the script "cleaner" but either way the result stays the same . if i for an example echo %%a i can see that my variable contains the right input. if i change my variable to the actual text, my commands run as they should. it is as if this sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{63C9BB9F-7582-43F7-8950-C524E83018B7}" and this sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\%%a" is not the same... i know if you run the script it will say that method execution successful
with a returnvalue of 2 the returnvalue should be 0 for it to be successful though.
again thanks for your effort Squashman it is appreciated I did manage to resolve my issue the script below works. It turns out that my variable didnt like curly parentheses.
Thanks for your help Squashman for pointing in the right direction

echo off
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=2 delims==" %%a in ('WMIC NIC where "Manufacturer='Intel Corporation'" GET GUID /VALUE') DO ( set GUID=%%a
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetDWORDValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{!GUID:~1,36!}" sValueName="EnableDHCP" uValue="1"
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{!GUID:~1,36!}" sValueName="IPAddress" sValue=""
   WMIC /NAMESPACE:\\root\default Class StdRegProv Call SetMultiStringValue hDefKey="&H80000002" sSubKeyName="SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{!GUID:~1,36!}" sValueName="SubnetMask" sValue=""
)
ENDLOCAL

1118.

Solve : net use not going to EOF?

Answer»

in an simple "IF" statement, I want, after the text, for it to GOTO :EOF.
This doesn't HAPPENS. it simply says : COMMAND completed successfully.

Here's the code
Code: (batch) [Select]echo off
if exist s:\1.txt (GOTO :exit
) else (
GOTO :net_use)
:net_use
net use s: \\que-mdt-01\fna_mdt\Logs
echo Do Not Delete >>s:\1.txt
GOTO :EOF
:exit
echo Path already exist. Exiting.
PAUSE
exit
:EOF
pause
exit
Edited the if ... else block. Don't put stuff after the first or before the last parentheses. The ) else ( must all be on ONE LINE which you did right.

Code: [Select]echo off
if exist s:\1.txt (
GOTO :exit
) else (
GOTO :net_use
)
:net_use
net use s: \\que-mdt-01\fna_mdt\Logs
echo Do Not Delete >>s:\1.txt
GOTO :EOF
:exit
echo Path already exist. Exiting.
pause
exit
:EOF
pause
exit
Or you can do this

Code: [Select]echo off
if exist s:\1.txt (GOTO :exit) else (GOTO :net_use)
:net_use
net use s: \\que-mdt-01\fna_mdt\Logs
echo Do Not Delete >>s:\1.txt
GOTO :EOF
:exit
echo Path already exist. Exiting.
pause
exit
:EOF
pause
exitYou don't need any labels or gotos, you can just do this

Code: [Select]echo off
if exist s:\1.txt (
echo Path already exist. Exiting.
) else (
net use s: \\que-mdt-01\fna_mdt\Logs
echo Do Not Delete >>s:\1.txt
)
pause


1119.

Solve : Load Random File from Folder location Question?

Answer»

Was wondering if there was an easier way vs naming files 1, 2, 3, 4, 5, 6, 7 .... to launch an executable with random file appended to it within " " to when running an EXE have it pick from any number of many files at random. I right now can do this all in C++ with file names that are numbers. With C++ I can concatenate the random number output generated to .mp3 for example and then perform a system call to the player.exe "4.mp3" for example to play the 4th file NAMED 4.mp3. But I'd like the files to all keep their original file names without having to rename all files to numbers.mp3 since sometimes I want to manually go in and launch a file to listen to and navigating in a folder with numbers without a list of what is what it is all a mess of unknown.

I was wondering rethinking all of this if this could be done in Batch maybe where DIR can be used to append file name / extension to a text file and then at random read in one of the files listed in the DIR output, calling to say line #8.  So it launches whatever file name is the 8th down on the list. *Only the music files for example will be located in this folder and so there is no risk of calling to a non supported file type by the player.

iTunes isnt a solution for a random shuffle of music because this will be for more than just MP3 files, but also for video file formats when I want to watch something at random from say folders that are CATEGORIZED so say i want to watch an action movie but cant make up my mind, I run this and it picks from the list at  random and I watch it, or if i am not in the mood for whatever movie, I can run it again and it picks the next movie at random.Finally found what I think might be the solution... found this under search words of "opening a random file from windows", even though its really a batch script method ... NT based batch.

https://superuser.com/questions/872048/opening-random-file-from-folder-and-subfolders-with-batch-script-windows-7Elementary, surely? Capture the filenames, put them in an array (or a batch equivalent), generate a random number between array lower limit and array upper limit, use that as array index, read out the file name.


Yes that was my FIRST thought. Choosing one item out of a set like this is fairly straightforward, launching a file with the associated program is fairly easy as well for the most part.

Code: [Select]String sMask = "*.txt";
String sFolder = "D:\\";
var AllFiles = new DirectoryInfo(sFolder).GetFiles(sMask);
Process.Start(AllFiles[new Random().Next(AllFiles.Length)].FullName);

Also for funzies, a C++ version. Windows only. (my use of rand() results in non-uniform distributions) Hard-coded directory and file mask (D:\ and *.txt files).

Code: [Select]#include "stdafx.h"
#include <vector>
#include <string>
#include <algorithm>
#include <Windows.h>
#include <random>
#include <time.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{

WIN32_FIND_DATA finddata;

vector<wstring> files;
ZeroMemory(&finddata, sizeof(finddata));
HANDLE hfind = FindFirstFile(L"D:\\*.txt", &finddata);

while (NULL != hfind)
{
wstring smember(finddata.cFileName);
files.push_back(smember);
BOOL result = FindNextFile(hfind, &finddata);
if (!result)
{
FindClose(hfind);
hfind = NULL;
}
}

srand(time(NULL));
int chosen = rand() % files.size();
SHELLEXECUTEINFO inf;
ZeroMemory(&inf, sizeof(inf));
inf.cbSize = sizeof(inf);
inf.lpDirectory = L"D:\\";
inf.lpFile = (files[chosen].c_str());
inf.lpVerb = L"Open";
ShellExecuteEx(&inf);
}
Cool.... Thanks BC for showing how to do this in C++ without use of system(); calls.   It's interesting how much longer the C++ version is compared to the C# version (which admittedly WOULD need a few more lines to be a full program).

I tried to convert it to a powershell version but something came up so I just posted what I had at the time.

1120.

Solve : installing multiple software from network?

Answer»

Hi,
I WANT to install multiple SOFTWARE from a network <172.13.35.10>app1.exe,app2.exe,app3.exe using a batch file and automatically fill-in the USERNAME and PASSWORD of administrator when prompt.

Can someone help me on this.

THANKS, Do some research on "unattended installs"...
Tons of info out there...

1121.

Solve : Cannot read text in script?

Answer»

I don't think I have found a bug, but I have surely uncovered a problem.

I am trying to capture a list of drive letters and the corresponding volume names. It's simple using the command:
WMIC logicaldisk get deviceid, volumename
What comes back looks like TEXT - but it ISN'T !!!

I then try to process the output of the "WMIC" command using a cmd/bat "FOR" statement. I have coded and tested more than a dozen different attempts - tested for nearly half a day - on four different Windows computers (2 Win-7 and 2 Win-10) - and it simply does not work. The reason is that WMIC outputs something that looks like text --- BUT IT ISN'T --- and none of the WMIC format options work either. This is driving me crazy because I know the script works properly. I have included my script in the code below. You can run it "as-is" and check the output. Then, you can change the file being CREATED by making the WMIC line a comment and UN-commenting the line following it. The "dir" command does produce text and the script will work correctly.

I have tried editing the file produced by WMIC and that does not work either. I have tried creating a new file using NOTEPAD and just typing in the exact same information produced by the WMIC command. That creates real text and the script work perfectly.

I have hex-dumped all the files and can see no significant difference between the output of the WMIC command the other text lists I have created/used. Still... nothing coming out of WMIC can be processed by a cmd "FOR" statement - either by creating a separate output file or by coding the command inside the "FOR" statement.

I know some folks may offer different methods of getting the information I need. I appreciate that - but it will not solve the problem I have found. If anyone can tell me why the script I have created does not work I will be truly grateful. This is a challenge I have not been able to conquer - I hope someone else can.

THANKS IN ADVANCE..... Blue

Code: [Select]echo off
::
wmic logicaldisk get name,volumename > %temp%\disklist.txt
::dir c:\ >  %temp%\disklist.txt
::
set _dlist=%temp%\disklist.txt
::
echo This is the DiskList file generated by WMIC
echo (it should display twice)
echo File: %_dlist%
echo. & echo. & echo. & echo.
echo 1. typing DiskList file to console
type %_dlist%
::
::
echo. & echo. & echo. & echo.
echo 2. LISTING DiskList file using -For- command
For /f "tokens=1 delims=+" %%g in ( %_dlist% ) do (
  echo %%g
)
echo. & echo.
echo Is the second list above this line?
echo Not on my system
echo. & echo.
pause
exit
http://stackoverflow.com/questions/43011329/capture-result-of-wmic-command-to-variable
I DONT know if this can give you more information about WMIC outputHackoo - Great catch and outstanding research !!

I KNEW that encoding had to be the answer, but this is the key I could not figure out for myself...
"WMI results are encoded in a non-ANSI encoding (UCS-2 LE). Capturing the output of wmic also captures the output's encoding, resulting in the last character being moved to the beginning of the line or other unexpected behavior. The workaround for that is to use a second nested for /f to sanitize the value."

I will try implementing his method and, hopefully, get it working.

THANK YOU !!


FWIW: Only some douchebag at Microsoft could come up with a convention like this. It is scary. Exactly these sorts of things are the principal reason I have been migrating to Linux more-and-more over the last couple of years.WMIC is a thin wrapper around WMI which as a more "modern" API uses UTF-16 Unicode strings. Command Prompt, for backwards compatibility reasons, deals with ANSI.

WMI was designed primarily to be used from VBScript, and more recently Powershell. WMIC is more of a hack that provides some of the WMI functionality some of the time to some Command Prompt users. But it doesn't really do a great job of actually transforming the data to a form that is more usable in Command Prompt- (again, thin wrapper, exercise for the USER, etc.)

Bash sometimes presents similar encoding issues, if a program outputs in a format that isn't the same as the setting for Bash in /etc/rc.conf. (not sure where it is with systemd). But it defaults to UTF-8 which tends to work better. (Of course UTF-8 wouldn't work so well for Command Prompt since it woudl break loads of batch files that rely on it being ANSI)

1122.

Solve : Wifi Password Recovery?

Answer»

Hi 
I'm making a batch file to recover all the wifi passwords stored on computer !
I just have tested only on Windows 7 and Windows 10 (French Machines)
I wonder is there a trick to change this piece of code to get it working for all languages with windows is installed ?

Code: [Select]echo off
:Main
Title  WiFi PASSWORD Recovery by Hackoo 2017
Mode con cols=50 lines=30 &AMP; color 9E
echo [SSID] Menu :
set "pwd="
echo(
Setlocal Enabledelayedexpansion
for /f "skip=2 delims=: tokens=2" %%a in ('netsh wlan show profiles') do (
    if not "%%a"=="" (
        set "ssid=%%a"
        set "ssid=!ssid:~1!"
echo [!ssid!]
    )
)
EndLocal
echo(
Set /p "Input=Type your SSID Name : "
cls
Mode con cols=85 lines=5
for /f "tokens=2 delims=:" %%a in ('netsh wlan show profile name^="%Input%" key^=clear ^|find /I "Cont"') do (
set "pwd=%%a"
)
If defined pwd (
echo(
echo  The password of the SSID [%Input%] is ==^> "%pwd:~1%" without double quotes
) else (
echo(
color 0C
echo The password of the SSID [%Input%] is empty or not defined !
)
echo(
echo Hit any key to return to SSID Menu
Pause>nul & goto MainWhy not just write them down?Does it not work on machines that aren't in French?  I can't see any reason why it wouldn't. Quote from: camerongray on March 22, 2017, 05:11:16 AM

Does it not work on machines that aren't in French?  I can't see any reason why it wouldn't.
Here is the problem :
Consider if you have a German or spanich machine : this will not work with this piece of code :
Code: [Select]for /f "tokens=2 delims=:" %%a in ('netsh wlan show profile name^="%Input%" key^=clear ^|find /I "Cont"') do (
set "pwd=%%a"
)Because when you want to find this string with the command Find /I "Cont" you will not find it  I update this script in order to find and display all SSIDs saved on a PC with their passwords and save them in a text file. and here is its screenshot : Wifi Passwords Recovery.bat
Code: [Select]echo off & setlocal enabledelayedexpansion
Set "Copyright=by Hackoo 2017"
Title  %~n0 %Copyright%
Mode con cols=75 lines=8
cls & color 0A & echo.
echo             ***********************************************
echo                 %~n0 %Copyright%
echo             ***********************************************
echo(
if _%1_==_Main_  goto :Main
Set Count=0
Set L=0
:getadmin
    echo               %~nx0 : self elevating
    set vbs=%temp%\getadmin.vbs
(
echo Set UAC = CreateObject^("Shell.Application"^)
echo UAC.ShellExecute "%~s0", "Main %~sdp0 %*", "", "RUNAS", 1
)> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof
::*************************************************************************************
:Main
Call :init
Call :CountLines
Set "PasswordLog=%~dp0Wifi_Passwords_on_%ComputerName%.txt"
%Mod%
echo(
echo             ***********************************************
echo                 %~n0 %Copyright%
echo             ***********************************************
echo(
Call :Color 0E "                 [Num][SSID] ============== Password" 1
echo(
(
echo             ***********************************************
echo                 %~n0 %Copyright%
echo             ***********************************************
echo(
echo                  [Num][SSID] ============^> "Password"
echo(

)>"%PasswordLog%"
for /f "skip=2 delims=: tokens=2" %%a in ('netsh wlan show profiles') do (
    if not "%%a"=="" (
        set "ssid=%%a"
        set "ssid=!ssid:~1!"
call :Getpassword "!ssid!"
    )
)
echo(
echo Done
If EXIST "%PasswordLog%" start "" "%PasswordLog%"
pause>nul
exit
::*************************************************************************************
:Getpassword
set "name=%1"
set "name=!name:"=!"
Set "passwd="
for /f "delims=: tokens=2" %%a in ('netsh wlan show profiles %1 key^=clear ^|find /I "Cont"') do (
set "passwd=%%a"
Set /a Count+=1
)

If defined passwd (
set passwd=!passwd:~1!
echo                  [!Count!][!name!] ====^> "!passwd!"
echo                  [!Count!][!name!] ====^> "!passwd!" >> "%PasswordLog%"
) else (
Set /a Count+=1
call :color 0C "                 [!Count!][!name!] The Password is empty" 1
echo                  [!Count!][!name!] The Password is empty >> "%PasswordLog%"
)
exit /b
::*************************************************************************************
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::*************************************************************************************
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
    <nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
    echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::*************************************************************************************
:CountLines
for /f "skip=2 delims=: tokens=2" %%a in ('netsh wlan show profiles') do (
    if not "%%a"=="" (
set /a L+=1
)
)
set /a L=!L! + 10
Set Mod=Mode con cols=75 Lines=!L!
exit /b
::*************************************************************************************
[attachment deleted by admin to conserve space]Topic Closed.
1123.

Solve : Batch File to create, move folder name based on user input?

Answer»

I'm looking to create a batch file that will create, move folder name based on user input.

Example: What is your account? (user inputs an account name like 123RS456 or 78-910)
Test 1: The user inputs 123RS456
Test 2: The user inputs 78-910
Test 3: The user inputs 123-4567

That batch file creates folder based on characters in the account name and moves that folder.

Result for Test 1: C:\Accounts\Accounts_with_RS\456_123EA456 -the batch takes every character after 'RS' and renames it before an underscore

Result for Test 2: C:\Accounts\Accounts_without_RS\78910 -the batch will remove the "-" dash.

Result for Test 3: C:\Accounts\Accounts_without_RS\1234567 -the batch will remove the "-" dash.

I've gotten as FAR as having the user input into a .txt file thinking I could rename it, and make a directory from it, but that is as far as I can GET. Any help is appreciated

This is what I have so far,

echo off
title intro color 1f
echo You will have to type the account name below
set /p FILENAME="What is your account? "
echo %FILENAME% > temp.txt
REN C:\Accounts\temp.txt %FILENAME%.txt   - This does not work
I figured it out... See Below

echo off
title intro
color 1f
set /p ACCOUNTNUM="What is your account?"
ECHO.%ACCOUNTNUM% | FIND /I "RS">Nul && ( goto RSAccount ) || ( goto NoRS )

:NoRS
set FILEPREFIX=%ACCOUNTNUM:~0,2%
set FILESUFFIX=%ACCOUNTNUM:~3%
md %FILEPREFIX%%FILESUFFIX%
move "C:\Accounts\%FILEPREFIX%%FILESUFFIX%" "C:\Accounts\Accounts_without_RS\%FILEPREFIX%%FILESUFFIX%"
pause
exit

:RSAccount
set FILEPREFIX=%ACCOUNTNUM:~5,3%
set FILESUFFIX=%ACCOUNTNUM:~5%
md %FILEPREFIX%"_"%ACCOUNTNUM%
move "C:\Accounts\%FILEPREFIX%_%ACCOUNTNUM%" "C:\Accounts\Accounts_with_RS\%FILEPREFIX%_%ACCOUNTNUM%"
pause
exitYou could replace this:
Code: [SELECT]ECHO.%ACCOUNTNUM% | FIND /I "RS">Nul && ( goto RSAccount ) || ( goto NoRS )With this
Code: [Select] IF NOT "%accountnum:rs=%"=="%accountnum%" GOTO RSAccount

1124.

Solve : Am I in the right place ??

Answer»

I have tried searching to see if this site deals with the command interpreter scripts (??.cmd files). They are essentially the "new" batch files (real DOS doesn't exist in newer versions of Windows?). I don't want to ask questions in the wrong place, or waste anyone's time so I want to first find out if I can ask questions about .cmd files/scripts here. Most of what I have SEEN so far FOCUSES on ".bat" files, so let me know if this is not the right place (and PLEASE recommend a good site for answering .cmd questions).

Thank you in advanceYou chose well...weedhopper.

Carry on...For some reason the "Microsoft DOS"  section is 90% NT based batch scripts. If anything it get's confusing when people actually try to get help with a "real" MS-DOS Batch file, since replies will generally assume NT Command extensions.

For .cmd and .bat, they are effectively identical in how they operate on NT (with some minor differences with Errorlevels, I think). Both can be used with all NT Command extensions. The .cmd extension was mostly useful in the early days so that you could indicate WHETHER a batch was designed for windows NT or Windows 9x. Not so useful now when you have to reach back a decade or more for Windows versions without the added featuresets.Thank you for your replies. I wanted to assume what you have stated - but assumptions can be dangerous. So, now (tomorrow, actually) I can open a new topic to ask about a problem I am having.

Thanks, again.Are you sure you're not thinking of Powershell scripting?  In the very latest builds of Windows 10 MS has changed the default command interpreter to use Powershell instead of the old command.com.   Strollin, Methinks your avatar might be or might not be Mr. Natural - but it's gotta be Crumb !!

Powershell seems to be the latest generation/iteration of a DOS-like environment for Windows. I think it mainly adds support for the OO environment (objects) whereas true DOS knew nothing of that exotica.That is Mr. Natural.... My all-time favorite line - and I still use it frequently to express frustration - was a line from Mr. Natural,

"Mumble, B!tch, Gripe"

Over the years that line has described most of my emotions !!

1125.

Solve : File Names too long - following an attempted backup?

Answer»

Hi, I recently had computer issues and I decided to copy my music files on to an external hard drive. I now wish to access the files, but when I try I get a MESSAGE that the file name is too long and the  file(s) will not open. A more worrying aspect of this issue is that some files APPEAR to be empty. If anyone out there has a solution to this issue I WOULD be very grateful your for assistance. 

Thank you linx4,
Please provide information about what operating system you are using.
Also, what BACKUP program?
Hi,
I am using Windows 10. Foolishly I didn't use a backup program, just copy and paste from the computer hard drive to a blank dvd disc. Then the data was copied and pasted again to the new computer HD. Other files went over OK, but the music files did not and I am now unable to open them because the file name is too long. I believe that this error has been caused by the system  repeatedly accessing the files and adding to the file names. However, although I believe that to be the cause of the problem, how to cure it is unknown to me.

Regards

1126.

Solve : How do I make a save file??

Answer» OMG first post
For my game, I want to make a save file.
I already have this code:
Code: [Select](
  echo %Name%
  echo %HP%
  echo %LV%
) > %Name%Save.lsavto save.
How do I make the batch file read each line?
Please HELP!The > redirection operator has an opposite operator the < to pass from file back to the VARIABLE.

http://stackoverflow.com/questions/3068929/how-to-read-file-contents-into-a-variable-in-a-batch-file
Quote
Read file contents into a variable:

for /f "delims=" %%x in (version.txt) do set Build=%%x

or

set /p Build=<version.txt

Both will act the same with only a single line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.

Using the variable – just like any other environment variable – it is one, after all:

%Build%

also more here on this: http://www.robvanderwoude.com/redirection.php
Okay, let me rephrase.
How do I make it read every line?
I want this:

Save File:
1234
4321
1324

Now in the batch file:
(Sets the variables to the line)
%Line1% = 1234
%Line2% = 4321
%LINE3% = 1324 Quote from: Luigi master on June 11, 2016, 12:55:36 PM
Okay, let me rephrase.
How do I make it read every line?
I want this:

Save File:
1234
4321
1324

Now in the batch file:
(Sets the variables to the line)
%Line1% = 1234
%Line2% = 4321
%Line3% = 1324

There are many ways to skin this cat:   using this format when creating the save file allows you to rename the .lsav file and add a .bat extension, which you call and rename the file back again.  All your variables are set.

Code: [Select](
  echo set name=%Name%
  echo set HP=%HP%
  echo set LV=%LV%
) > %Name%Save.lsavI'm not sure this topic was resolved, or if the OP FOUND it helpful. To reiterate what Foxidrive said with an example:




:save
(
echo %health%
echo %bees%
)>textfile.txt


:load
(
set /p health=
set /p bees=
)
Use "Echo" to set the variable, "set /p" to load it. Also NOTE the direction of the carrots. ">" to save, "<" to load. Hope that helps!
1127.

Solve : Batch file to move files to folders wher foldername is the same until underscore?

Answer»

I want to move pdf-files to a folder where the foldername is the same as the filename until the _ in the filename.
The batch has to look into the filename and compare all caracters before the first _ (underscore).
If the caracters matches with a foldername move the file to that folder.
If not, create a new folder with this name.

Example filenames
Mertens John_contract_3apr17.pdf
Mertens Jake_contract_17apr17.pdf
Van de Ven Peter_Contract_24apr17.pdf
Van de Loo Ben_contract_28apr17.pdf

Example foldernames
Mertens John
Mertens Jake
Van de Ven Peter
Van de Loo Ben

I have no experience with batch-files and have found similar questions on the forum but no answer that works 100% for me.Hi 
You can give a TRY for this batch file : just save it with your notepad editor with this name MovePDF2Folder.bat in the same location of your PDF files and execute it by double clic
MovePDF2Folder.bat
CODE: [Select]echo off
for %%f in (*.pdf) do (
for /f "DELIMS=" %%a in ('echo %%f') do (
for /f "tokens=1 delims=_" %%b in ('echo %%a') do (
If not exist "%%b" ( MD "%%b")
move /Y "%%a" "%~dp0%%b"
)
)
)
pause & exitI found another approch on Stackoverflow posted by Mofi
Code: [Select]echo off
for /F "tokens=1* delims=_" %%A in ('dir /B /ON *_*.pdf 2^>nul') do (
md "%%A" 2>nul
        move /Y "%%A_%%B" "%%A"
)
pauseWorks perfect
Thank you so much, Hackoo!!

Quote from: buyt006 on APRIL 14, 2017, 04:59:07 AM

Works perfect
Thank you so much, Hackoo!!
You are welcome dude    and don't forget to use the Thanks link 
Have a nice DAY
1128.

Solve : Accessing a CD with an MS-DOS Computer, without Windows?

Answer»

Is it possible to write and read text files on a CD on a computer that has MS-DOS 6.0 and WordPerfect, but not Windows?
 
     Background: I use WordPerfect 6.0 extensively in my small business.  I'm very familiar w/WP60, including its flaws and quirks, having used it since 1990, and don't want to change.  Windows, amazing as it is in general, just adds extra steps and is not needed w/WP60 (e.g., it's very easy to cancel a print JOB in WP60, but Windows requires you to go into Control Panel and do some things).
     In addition, I don't want my business data to be subject to malware, so my DOS-only computers are not connected to anything other than the power cord.  Yes, this has happened - over a year ago, we were using a Win XP computer w/WP60, keying in invoices.  This computer had been retired from Internet use several years EARLIER.
     After about a year of use w/WP60, it began crashing now and then.  The crashes become too frequent to continue using it.
Thinking WP60 files had become corrupted, I deleted all WP files and reloaded WP; more crashing.  I copied the invoice files to another computer, that too became infected.  To shorten the story, I eventually recovered my files from copious floppy backups onto a 3rd DOS-only computer.  Other than sleep, I lost very little.  Despite what the WP gurus say, I'm telling you WP files CAN BE INFECTED with malware - I later ran the Win XP scan, and found 2 malware programs.

     Thus, I would like to be able to save all my text files to a CD at once, rather than having to have a zillion floppies.

     Thank you in advance for any suggestions!

TimAbsolutely.  Refer to this tutorial: http://manmrk.net/tutorials/DOS/cdrom.htmAlso, the OP might like to know there are, evidently, many people still using MS-DOS 6.22 and they can boot it from a CD-ROM.
If you have a legal set of the DOS 6.22 disks, it is OK to make a CD boot. You can learn more from a Microsoft web forum.

https://social.technet.microsoft.com/Forums/windows/en-US/e4696428-6999-4946-81c1-ea934eb6fd41/dos-622?forum=itprovistamigration

Quote

Thanks for posting in Microsoft TechNet forums.

Please check if the following REQUIREMENT is ready:
1.     Download an MS-DOS 6.22 ISO
you can download this from AllBootDisks website:
http://www.allbootdisks.com/download/iso.html
Please Note: Since the website is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
2.      We will need a program that can burn ISOs to CD/DVD drives,  Check out Ultimate List Of Free CD/DVD Burning Programs
Hope that is some help.The OakRom CD drivers for CDRom show the most success...in my experience.I think maybe the OP is asking about burning CDs in MS-DOS, which is not very easy... For a start the CD drive needs to be a burner, not a CD-ROM device. Secondly the software arrangements are not always simple.
Quote from: little timmy on March 28, 2017, 10:29:55 AM
Is it possible to write and read text files on a CD on a computer that has MS-DOS 6.0 [...] I would like to be able to save all my text files to a CD...
Perhaps Timmy could clarify?
An old guy was trying to use a computer.  The message on the screen was "press any key to continue".  Not finding a key labeled "ANY", he quit in disgust.  I'm not quite that clueless, but I'm 72 and really have a lot to learn - I remember when a computer took up a whole room.  I keyed in on a teletype - no video display.  Made a mistake? Re-type the entire line.

Even little items like "OP" (other person?  operator?  on the 3rd guess, dawn broke: original poster.  Makes sense.  The greatest thing about the Internet is you can look stuff up as you go.

Many thanks to all who replied - I reviewed all the links which you supplied, which raised many more questions for me to try to answer on my own.  From my standpoint, I see no quick and easy way to implement CD use.  Poke around in autoexec.bat and config.sys files?  I think I did that maybe 20 years ago - I wouldn't try it today on a computer that I want to keep using, but I will study the process and try to do it.

Salmon asked if I want to access a CD from MS-DOS - I don't mind if I have to have another piece of software to do that; I just didn't want to run WordPerfect under Windows.

Here again I'm confused - I recall someone telling me DOS 7 supported CD ROMs (somewhere here I have a computer w/7 installed, but the only version I own is 6.0, complete with MANUAL).

I see that OldSoftware.com has both DOS 6.22 full sets and 6.22 'step up' discs for sale - all certified stuff.  Prices seemed very reasonable; seems like it would be a good investment.  Anyone have experience with this company?

Final question:  What, if any DOS versions support thumb drives?  If I could save to a thumb drive, then I could upload to my Win 7 computer and burn a CD.

Many thanks and kind regards,
TimI don't think it was an infection...
Only way that would occur on a PC not on the web is if someone loaded/used a floppy with an infection on it...highly unlikely. Quote from: little timmy on March 30, 2017, 09:58:10 AM
Salmon asked if I want to access a CD from MS-DOS
I asked if you wanted to write CDs under MS-DOS. Just reading them is pretty simple and easy to arrange. You talked in your original post about saving important files to CD.

There is a well-known Panasonic USB driver for MS-DOS that may allow you to use a pen drive. Google for "Panasonic v2.06 ASPI Manager for USB mass storage"
Salmon, thank you for your replies.  Yes, I want to both write and read to CDs from a DOS-only (no Windows) computer.  I have 2 locations, and when I leave one to go to the other, I've been taking the computer with me, because it has all my business records on it.  It would be so much easier to just take a CD.  It do have floppy backups, but it's cumbersome to upload these to another computer.

I looked at the Panasonic driver for a thumb drive - the feasibility of this seems to be iffy, plus I don't want to download unauthorized/unpurchased software.

I also considered an external hard drive, but I suppose that would require a driver also.


Regarding Patio's suggestions about the infection on the Win XP computer:  that computer had been connected to the web several years before it was used (unconnected) for billing.  Obviously the malware executed when it was used for billing.  I have run the Win XP built-in malware program; here is what it finds and removes: Trojan: DOS/Alureon.A.; however, the program says I need to run Standalone System Sweeper, which I downloaded to a Win 7 computer on CD, and uploaded it to the Win XP computer, but wasn't able to get it to execute.

Regards,

Tim




Quote from: little timmy on April 06, 2017, 10:21:45 AM
I looked at the Panasonic driver for a thumb drive - the feasibility of this seems to be iffy, plus I don't want to download unauthorized/unpurchased software.
The Panasonic driver is free, and has been made available for download by Panasonic. If you think installing that would be iffy, getting a CD writer drive to work would be somewhere between very difficult and impossible.
OK, Salmon, and many thanks.  I will give the Panasonic driver my best shot.

Regards,
Tim
1129.

Solve : Batch File to Open a word template file and run a macro in that template?

Answer»

I am trying to create a batch file to open a Word template file (.dotm) and run a macro file in that template.

File:  D:Accounts\sales.doc
Macros &AMP;template stored in C:\Users\%username%\AppData\Roaming\Microsoft\Word\STARTUP\salesmacros.dotm

Batch File script:
echo off
 start /B "Word" "D:Accounts\sales.doc"
/t"C:\Users\%username%\AppData\Roaming\Microsoft\Word\STARTUP\salesmacros.dotm"
/m"C:\Users\%username%\AppData\Roaming\Microsoft\Word\STARTUP\salesmacros.dotm.Macro_sales"

The script isn't working.  Any help??
What guide did  you use to crease the script?
DD you use this?
https://support.microsoft.com/en-us/help/210565/how-to-use-startup-command-line-switches-to-start-word-2010,-word-2007,-word-2003,-word-2002,-and-word-2000

Notice different versions of Word are in different directories.

But why batch? Just to see if you can do it?
OK,that is a good reason. Just not the best on
 Word is a Windows program, not a DOS program. Windows shortcuts  offer an easy way to start Word with automatic start-up settings.

Also, you script hard to read. Can you tells us what it is supposed to do?

You cannot pass command line arguments when you start a program by "executing" an associated document via the start command.

Instead, you'd have to start WINWORD.EXE directly with the arguments and the target file you want to open.

ddjedidd,
Are you still there? Did you find a solution?
When at the command prompt, the "START" command might not be  the right way to start a program the runs in Windows.
"START" has its own SET of command line options which differ from winword.exe, the Microsoft Word program.

Example: There is a file 'test.doc' in the current directory. Here is a batch file to start Word and open that file and ignore other stuff.
Code: [Select]REM invokde MS word program with test.doc
"C:\Program Files\Microsoft Office\Office10\WINWORD.EXE" /a test.doc
 Is that almost what you want?I am still here.  That is not quite what I am looking for.  The intent is for a Macro in a Global template to run automatically.  I do not want that to happen every time a user opens Word, so I was thinking a Batch script that calls up the Macro would be an idea.

I have been playing with an Autorun Macro, but I cannot get it to call the Macro in the Global Template Module.

I haven't given up yet.Please give some detail about what kind of business you are running. In general terms. Is this  a place where five people work on two computers and have to generate a report each week?
Are all computers on the same network?
Is the job done daily, weekly or monthly?
What kind of errors would likely occur?
Could other people run the batch?

Batch requests seem to always be nebelous...
Describe completely what the goal of this Task is and what RESULTS you are expecting...
Ok.  I work with several users who share a network.
I have developed a Macro embed Global Template (.dotm file) that is stored on each computer. Located in:
C:\Users\%username%\AppData\Roaming\Microsoft\Word\STARTUP\salesmacros.dotm

My intent:  The user clicks on a BUTTON (or link) on the Shared Network that will:
1. Open Word
2. Find their template (on their C:Drive as noted above)
3. Automatically run the top level macro (called "Macro_sales")

I thought a clean way to accomplish those three steps in one, would be a Batch File.

Just as FYI - The "Macro_sales" macro asks the user a series of questions (IF and IFELSE VBA) to populate a specific report template (based on the users answers), creates a network folder, and save the populated form and a .doc file.

Again, thank you for any help
 OK. That does help. So you have a number of users and there can be some variation in how each workstation is set up.
Yes, it can be done from dos, but DOS does not have a way to syndicate  a number of commands to a program. All options must be on one line.
Put another way, it is going to be a one line thing.

Here is the general information about command line options in Word 2010 and up.
https://support.microsoft.com/en-us/help/210565/how-to-use-startup-command-line-switches-to-start-word-2010,-word-2007,-word-2003,-word-2002,-and-word-2000
MS suggests  using a link (shortcut) instead of batch. (But you can batch a link.)
Quote

Follow these steps to create a shortcut to start Word from the Windows desktop:
    Right-click the Windows desktop, point to
    New on the shortcut menu that appears, and then click
    Shortcut.
    In the Create Shortcut dialog box, click
    Browse.
    In the Browse dialog box, change the
    Look in box to the following folder:
    C:\Program Files\Microsoft Office\Office
    Note This location of this folder may be different on your system.
...
Read over List of Word startup switches
I think it says that you can open a file, set a template and auto run a macro on on one command line.

I will try something after I think about this some more. 
Meanwhile, maya e a quick mind might jump in. 
OK. A simple experiment.
Now I can do a BAT fle and open a document and do a macro all none command line. I put the document in D:REPORT to reduce the long path name.
Here is what works as a batch file:
Code: [Select]"C:\Program Files\Microsoft Office\Office10\WINWORD.EXE" D:\rEPORT\report.doc /mmacro1
The macro starts automatically and inserts some text then stops.
I have not tired using a template.   Hi 
This a starting batch to create a Winword shortcut with arguments on the desktop :
So, give a try and modify it as you need
Code: [Select]echo off
Title Creating a Winword shortcut with arguments on the desktop
Mode con cols=70 lines=5 & color 9E
REM Determine if the OS is (32/64 bits) to set the correct path of Program files.
IF /I "%PROCESSOR_ARCHITECTURE%"=="x86" (
        Set "strProgramFiles=%ProgramFiles%"
    ) else (
        Set "strProgramFiles=%programfiles(x86)%"
)

set Key="HKEY_CLASSES_ROOT\Word.Application\CurVer"
For /f "tokens=4 delims= " %%a in ('reg Query %Key% /ve ^| findstr /R "[0-9]"') do (
for /f "tokens=3 delims=." %%b in ('echo %%a') do (
Set "Ver=%%b"
)
)

Rem The shortcut name with the .lnk extension
Set "MyShortcutName=%userprofile%\desktop\%~n0.lnk"
set "TargetPath=%strProgramFiles%\Microsoft Office\Office%ver%\Winword.EXE"
Rem Here we put the arguments of the command line
Set "Arguments=/q /a"

If not exist "%MyShortcutName%" (
Call :CreateShortcut
) else (
Goto Main
)
Exit

::***********************************************************************
:CreateShortcut
echo(
echo         Creating the shortcut on the desktop is in progress .....
::***********************************************************************
Powershell ^
$s=(New-Object -COM WScript.Shell).CreateShortcut('%MyShortcutName%'); ^
$s.TargetPath='"%TargetPath%"'; ^
$s.Arguments='%Arguments%'; ^
$s.Save()
Exit /b
::***********************************************************************
:Main
echo Hello
pause
1130.

Solve : Deleting characters from a string through a batch command?

Answer»

I'm trying to write a batch command that deletes characters from a file and then outputs the new file into a folder.

The file in Question is below:

bjobojd0000004609142355sd.txt

Everytime the batch file is ran i need it to remove all the characters from the 16th and the 24th position so it reads bjobojd00000046sd instead. If anyone knows how to do this would you be kind enough to let me know how to perform this.

Many Thanks

BeastyThis was done by extracting the characters you want to remove and using them as a search argument to be replaced by nulls. The set statement uses zero based offsets, not one based positions.

Code: [Select]echo off
setlocal

set oldFile=bjobojd0000004609142355sd.txt
set mask=%oldFile:~15,8%

call set newFile=%%oldFile:%mask%=%%
echo copy %oldFile% %newFile%

The code is based on the file names posted. Fixup any paths as necessary.

Good luck.  Thanks very much i will give it a go

BeastyTo beasty: did you want to lose the.txt extension? Because that is what your post implies.

Before

Quote from: beasty

bjobojd0000004609142355sd.txt

After

Quote from: beasty
so it reads bjobojd00000046sd instead
Yes i would like to lose the .txt

One of our systems regularly creates a file of around 26 characters long which is to long for a contractors system to input into there system. So BASICALLY what i was asking was everytime a similar file is created, a batch command removes the characters from the 16th and 24th position in the string so it can be accepted into the Contractors system.

I'm not the BEST with batch files, Sidewinder below has given me something to try. The mask instruction is working perfectly but what i have found out today is that there will be multiple files in a directory that will need changing simultaneously and all will have different date and time values in the characters being removed. Any help would be appreciated  The for instruction changes the the entire personality of a batch file. A subroutine was used to cut down on the complexity of the code.

Code: [Select]echo off
setlocal enabledelayedexpansion

for /f "tokens=* delims=" %%v in ('dir /b *.txt') do (
  set oldfile=%%v
  for /f "tokens=* delims=" %%i in ("!oldFile!") do (
    set newFile=%%~ni
    call :doit
  )

goto :eof

:doit
  set mask=%oldFile:~15,8%
  call set newFile=%%newFile:%mask%=%%
  echo copy %oldFile% %newFile%
 

The last line of the code is prefaced with an echo command. This allows you to see the possible results without ACTUALLY creating any files. Remove the word echo when satisfied. 

When removing characters from file names be aware you run the risk of creating duplicate file names. Code is set up to run from the same directory as the .txt files are located.

Good luck. 

BTW: positions 16-24 is 9 characters, but the example posted only shows 8 character for removal. If the number of removed characters varies, a better solution would be VBScript which has functions for better inspecting the data.If you wouldn't mind could you give me a little bit more of an explanation.

Where it says ('dir /b *.txt') i take it the 'dir stands for the directory in which the multiple files are located?

If i gave you an example i.e. There are multiple files in a folder called c:\bobjects\sample jobs and all the files need to have the characters removed. Does that need to go in ('dir /b *.txt').

What about outputting the amended files into a different folder?

Excuse my lack of knowledge in this area as i do not tend to get involved to much with batch scripts and i'm struggling!!! 

You have been more than helpful by the wayThis should fix it up. Added a pushd instruction to set the CURRENT folder to where the txt files live, and a popd instruction to navigate the user back to the starting folder. The batch file and the text files do not have to live in the same folder.

Also changed the last line of code so you can see how to direct the output to the folder of your choice.

Code: [Select]echo off
setlocal enabledelayedexpansion
pushd c:\bobjects\sample jobs

for /f "tokens=* delims=" %%v in ('dir /b *.txt') do (
  set oldfile=%%v
  for /f "tokens=* delims=" %%i in ("!oldFile!") do (
    set newFile=%%~ni
    call :doit
  )


popd
goto :eof

:doit
  set mask=%oldFile:~15,8%
  call set newFile=%%newFile:%mask%=%%
  echo copy %oldFile% drive:\path\%newFile%

It still holds true that removing characters from otherwise unique file names runs the risk of duplicates and file overwrites. 

Happy coding  Right i've got a little bit further, the first bit seems to work and it copies the files but it won't copy files into another folder.

echo off

setlocal enabledelayedexpansion

pushd C:\bobjects\SampleJobs


for /f "tokens=* delims=" %%v in ('dir /b *.*') do (
  set oldfile=%%v
  for /f "tokens=* delims=" %%i in ("!oldFile!") do (
    set newFile=%%~ni
    call :doit
  )


pause

popd
goto :eof


:doit
  set mask=%oldFile:~15,8%
  call set newFile=%%newFile:%mask%=%%

echo copy %oldFile% c:\bobjects\test\%newFile%

Have i missed something Quote from: beasty on July 05, 2011, 10:30:54 AM
Right i've got a little bit further, the first bit seems to work and it copies the files but it won't copy files into another folder.

echo copy %oldFile% c:\bobjects\test\%newFile%

Have i missed something

Remove the echo?

Thanks i'm getting somewhere now Hi

I'm still having a couple of problem's but i am getting further.

I need to incorporate a call command with in the script below:

echo off

rem W-Dixon Test repairs out
rem echo Press Ctrl+C or close the window to stop or
rem pause
echo Working........................

net use D: \\"ipaddress"\test_var /persistent:no

C:
cd \wdftp
rmdir wdtestoutold /s /q
ren wdtestout wdtestoutold
mkdir wdtestout
cd \wdftp\wdtestout

rem Copy test files from orchard/Test_var to wdftp folder for ftp to W-Dixon
xcopy D:\l\test\var\pmcli\ifc\output\wd\* c:\wdftp\wdtestout /v /y
xcopy c:\wdftp\wdtestout\* c:\wdftp\wdtestoutold /v /y
ftp -i -s:"c:\batch\wdtest.ftp" ip address
del /q D:\l\test\var\pmcli\ifc\output\wd\*
del /q c:\wdftp\wdtestout\*

echo .
echo wdtestout finished

rem pause

The call command needs to go just under the second xcopy in the file and needs to call the script earlier in the post using call instead of push and then needs to be out putted to an FTP folder:

pushd C:\wdftp\wdconvert


for /f "tokens=* delims=" %%v in ('dir /b *.*') do (
  set oldfile=%%v
  for /f "tokens=* delims=" %%i in ("!oldFile!") do (
    set newFile=%%~ni
    call :doit
  )


popd
goto :eof
:doit
  set mask=%oldFile:~15,8%
  call set newFile=%%newFile:%mask%=%%
 copy %oldFile% c:\wdftp\wdconvert\%newFile%

Would someone be kind enough to show me how to do this?

Thanks

Beasty

beasty,

You do yourself a disservice by requesting stuff in dribs and drabs. Many responders will see your thread has 12 replies and figure they have nothing to add or the problem was solved. Better to split your request into multiple posts or ask all your questions in your first post.

Unless I missed a day in Batch Coding 101, The call statement and the pushd statement are unrelated. The call is used in a batch file to give control to a secondary batch file located somewhere in your system. It sets up a mechanism so when the secondary file terminates, control is passed back to the calling program at the statement following the call which then continues executing.

The pushd statement is like the cd statement with benefits. Pushd saves the current directory on the stack and then changes to the directory passed as the first argument on the command line. The opposite of pushd is popd which navigates to the directory pulled from the stack. The order is last in, first out (LIFO), so it pays to keep TRACK of this info. It's useful on forums where the OP fails to mention path information.

Ex: c:\temp> pushd c:\windows
   this will save the c:\temp directory on the stack and then navigate to the c:\windows directory.

Insert the call statement after the second xcopy as call scriptfromearlierpost.bat If the called file is not in the current directory you will need to supply path information. Same as for the file that ends up in the FTP folder.


  Quote from: Sidewinder on July 11, 2011, 11:07:24 AM
The call is used in a batch file to give control to a secondary batch file located somewhere in your system. It sets up a mechanism so when the secondary file terminates, control is passed back to the calling program at the statement following the call which then continues executing.

In addition to the above, CALL can also call a subroutine within the batch file and as beasty is trying to do, CALL can also be used to run any internal command (SET, ECHO etc) expanding any environment variables passed on the same line.
1131.

Solve : DOS Command to capture image names & output to Excel ??

Answer»

Hi - i have 1000's of product images (mostly JPG / PNG) STORED in a folder.

Anyone care to share a DOS Command to capture the image file names & output to an Excel ? 

This will save me alot of time in individually copying / pasting the name to Excel Sheet. 

THANKS in Advance.

 The simplest way to do what you asked for is this:  for %%x in (*.jpg) do echo %%x ,  >> out.csv      (save this command to a batch file, if you want to run it from the command line use only a single % sign in front of the x's).

This creates a CSV file named out.csv which is a text file containing Comma Separated Values (CSV).  Excel can read a CSV file in directly.

This command only reads the files in the current folder and only those with the extension .jpg.  You could run it multiple times with different extensions or change the command to add all the extensions you're looking for such as: for %%x in (*.jpg *.gif *.png) do echo %%x ,  >> out.csvThanks..

It seems you've figured out what I want to accomplish.

My DOS skills is completey ZERO, although I am an Oracle Programmer.

Do you mind giving a more concise answer ?

Ie :

1. Goto C: prompt
2. Type: for %%x in (*.jpg) do echo %%x ,  >> out.csv ??!!
3.   Then...

What do you mean by current folder ?

Although , I appreciate your answer,    I have no idea on what to do ?!

The current folder is WHICHEVER folder you happen to be in at the time.  So, for instance, you you open a command prompt and type in cd \, you will change to the root folder.  The current folder will be the root folder.

What folder are the images you wish to capture the names of in?  Let's assume the folder is called C:\Images.  Open a command prompt and navigate to C:\Images to make it the current folder, then type in the command: for %x in (*.jpg *.gif *.png) do echo %x ,  >> out.csv    This will create a file in the folder called out.csv.  If you go into Windows Explorer and find that file and double-click on it, it will open in Excel and all of your image files will be listed there.Hi 
You can start from this script, just give a try and tell me the results 
ImagesFinder.bat
Code: [Select]echo off
mode con cols=75 lines=4 & Color 0A
Title Search for images files
REM We set the variable Folder
Set "Folder=%USERPROFILE%\Pictures"
Rem We set the variable EXT for the extensions images to be searched by the script
Set "EXT=jpg png gif"
REM We initialize the variable Count from zero for counting images files
SET "Count=0"
Rem Set the variable LogFile to save the information after the scanning
Set "LogFile=%~n0.csv"
If exist "%LogFile%" Del "%LogFile%"
Setlocal Enabledelayedexpansion
For %%a in (%EXT%) Do (
Call :Scanning %%a
FOR /f "delims=" %%f IN ('dir /a-d /b /s "%Folder%\*.%%a"') DO (
Rem We increment the variable Count
SET /a "Count+=1"
rem populate the array variable list with the name of images
set "list[!Count!]=%%~nxf"
rem populate the array variable listpath with the whole path of images
set "listpath[!Count!]=%%~dpFf"
)
)
Cls
echo(
echo             Saving information into the file "%LogFile%"
echo             The Total of [%EXT%] images files(s) found is !Count!
rem Display array elements
for /L %%i in (1,1,%Count%) do (
rem save information into the LogFile.csv
echo %%i;!list[%%i]!;!listpath[%%i]!>> "%LogFile%"
)
Start "" "%LogFile%" & exit
::****************************************************************************
:Scanning %1
Cls
echo(
echo           Please Wait a while Scanning for "*.%1" images ...
Timeout /T 1 /nobreak>nul
exit /b
::****************************************************************************Let's hope there aren't any bmp images.
Quote from: Hackoo on March 26, 2017, 02:31:18 AM

Hi 
You can start from this script, just give a try and tell me the results 
ImagesFinder.bat...   
Nice little .bat file Hackoo.  I'd recommend changing the line echo %%i;!list[%%i]!;!listpath[%%i]!>> "%LogFile%" to use commas instead of semi-colons, that way Excel will put the count, file name and location in separate columns.

As for Salmon's comment regarding .bmp files, any other type of image files can be added to the line: Set "EXT=jpg png gif bmp tif" or in my original command: for %x in (*.jpg *.gif *.png *.bmp *.tif) do echo %x ,  >> out.csvNew script to search for [jpg png gif bmp tif] with ShowBalloonTip function in powershell for fancy 
ImagesFinder.bat
Code: [Select]echo off
Title Search for images files
mode con cols=75 lines=5 & Color 0A
REM We set the variable Folder
Set "Folder=%USERPROFILE%\Pictures"
Rem We set the variable EXT for the extensions images to be searched by the script
Set "EXT=jpg png gif bmp tif"
REM We initialize the variable Count from zero for counting images files
SET "Count=0"
Rem Set the variable LogFile to save the information after the scanning
Set "LogFile=%~n0.csv"
If exist "%LogFile%" Del "%LogFile%"
Set "Msg=Please wait a while scanning for"
Setlocal Enabledelayedexpansion
For %%a in (%EXT%) Do (
Call :Scanning %%a
Call :ShowBalloonTip 'Information' 100 '"%~n0 to find images"' '"%Msg% """*.%%a""" images ..."' 'Info' 10
FOR /f "delims=" %%f IN ('dir /a-d /b /s "%Folder%\*.%%a"') DO (
Rem We increment the variable Count
SET /a "Count+=1"
rem populate the array variable list with the name of images
set "list[!Count!]=%%~nxf"
rem populate the array variable listpath with the whole path of images
set "listpath[!Count!]=%%~dpFf"
)
)
Cls
echo(
echo             Saving information into the file "%LogFile%"
echo        The Total of [%EXT%] images files(s) found is !Count!
rem Display array elements
for /L %%i in (1,1,%Count%) do (
rem save information into the LogFile.csv
echo %%i,!list[%%i]!,!listpath[%%i]!>> "%LogFile%"
)
Start "" "%LogFile%" & exit
::****************************************************************************
:Scanning %1
Cls
echo( & echo(
echo             %Msg% "*.%1" images ...
exit /b
::****************************************************************************
:ShowBalloonTip $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*****************************************************************************Maybe I can contribute something POSITIVE..............

If you have multiple folders in different locations and don't want the bother of putting the script in the "current folder" you're welcome to drop this code into your script. This will let you put your script wherever you want - then - at run-time - you can browse your computer and pick the target folder you want to work with.

Obviously, you have to tweak the original script to include this code - and use the variable that returns the folder you picked. And don't forget... make SURE the "EXITs" in this script are removed or modified so when this code ends it doesn't terminate the script it was inserted into.

Cheers !!

Code: [Select]echo off
setlocal enabledelayedexpansion
::
set SName=%~dpn0
::
call :SavBrowse
::
cls & color 2E
::
:: =====================================================================
::   call the folder-finder
:: =====================================================================
::
set _Repo=
For /f "delims=" %%A in (
 'cscript //nologo "%temp%\900_VBrowse.vbs" "C:\"'
) do set _Repo=%%A
::
echo. & echo.
echo Selected Folder:   %_Repo%
echo. & echo.
echo. & echo.
pause
::
::
:: =====================================================================
::  End-of-Script
:: =====================================================================
::
cls & color 5E
echo. & echo. & echo. & echo.
echo. & echo   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
echo. & echo   *  %~nx0
echo. & echo   *    Blah, Blah, Blah........
echo. & echo   *   
echo. & echo   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
echo. & echo.
set /p entered=....Hit any key to continue   
::
EXIT
::
::
::
::
::
:: -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
::    Subroutines
:: -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
::
:SavBrowse
::
set _aa=Function BrowseForFile()
echo %_aa% > %temp%\900_VBrowse.vbs
set _aa='
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=xparm = ""
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=xparm = WScript.Arguments.Item(0)
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa='
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=Dim shell : Set shell = CreateObject("Shell.Application")
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=Dim file : Set file = shell.BrowseForFolder(0, "Choose a folder:", ^^^&H4000, xparm)
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa='
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=BrowseForFile = file.self.Path
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=End Function
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa='
echo %_aa% >> %temp%\900_VBrowse.vbs
set _aa=WScript.echo(BrowseForFile)
echo %_aa% >> %temp%\900_VBrowse.vbs
goto :EOF

As someone who has tinkered with batch/vbs hybrid scripts, I have to ask: why all those set _aa and echo %_aa% commands? Why not just echo the lines directly into the vbscript? It makes the batch harder to read and doubles the number of lines in that section.



 Also, double-colons (which are really broken labels) as comments are severely deprecated in NT family batch scripting; they may look cool but they can break scripts, e.g. in parenthesis blocks.

Not wishing to pour cold water on what is a very neat idea.

If you want to use the function Browse4Folder, you can do something like this   
ImagesFinder.bat
Code: [Select]echo off
Title Search for images files
mode con cols=75 lines=5 & Color 0A
REM We set the variable Folder
Call :Browse4Folder "Choose source folder to scan for images files" "c:\scripts
Set "Folder=%Location%"
Rem if the variable %Folder% have a trailing back slash, we remove it !
IF %Folder:~-1%==\ SET Folder=%Folder:~0,-1%
If "%errorlevel%" EQU "0" (
echo( & echo(
echo             You choose this folder "%Folder%"
Timeout /T 2 /nobreak>nul
) else (
echo( & echo(
echo                              "%Folder%"
Timeout /T 2 /nobreak>nul & Exit
)
Rem We set the variable EXT for the extensions images to be searched by the script
Set "EXT=jpg png gif bmp tif"
REM We initialize the variable Count from zero for counting images files
SET "Count=0"
Rem Set the variable LogFile to save the information after the scanning
For %%f in (%Folder%) do set "LogFile=%~n0_%%~nf.csv"
If exist "%LogFile%" Del "%LogFile%"
Set "Msg=Please wait a while scanning for"
Setlocal Enabledelayedexpansion
For %%a in (%EXT%) Do (
Call :Scanning %%a
Call :ShowBalloonTip 'Information' 100 '"%~n0 to find images"' '"%Msg% """*.%%a""" images ..."' 'Info' 10
FOR /f "delims=" %%f IN ('dir /a-d /b /s "%Folder%\*.%%a"') DO (
Rem We increment the variable Count
SET /a "Count+=1"
rem populate the array variable list with the name of images
set "list[!Count!]=%%~nxf"
rem populate the array variable listpath with the whole path of images
set "listpath[!Count!]=%%~dpFf"
)
)
Cls
echo(
echo             Saving information into the file "%LogFile%"
echo        The Total of [%EXT%] images files(s) found is !Count!
rem Display array elements
for /L %%i in (1,1,%Count%) do (
rem save information into the LogFile.csv
echo %%i,!list[%%i]!,!listpath[%%i]!>> "%LogFile%"
)
If exist "%LogFile%" (
Start "" "%LogFile%" & exit
) else (
exit
)
::****************************************************************************
:Scanning %1
Cls
echo( & echo(
echo             %Msg% "*.%1" images ...
exit /b
::****************************************************************************
:ShowBalloonTip $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*****************************************************************************
:Browse4Folder
set Location=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
(
    echo set shell=WScript.CreateObject("Shell.Application"^)
    echo set f=shell.BrowseForFolder(0,"%~1",0,"%~2"^)
    echo if typename(f^)="Nothing" Then 
    echo wscript.echo "set Location=Dialog Cancelled"
    echo WScript.Quit(1^)
    echo end if
    echo set fs=f.Items(^):set fi=fs.Item(^)
    echo p=fi.Path:wscript.echo "set Location=" ^& p
)>%vbs%
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del /f /q %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
goto :eof
::******************************************************************************I am not a "scriptor" - I just solve problems as I encounter them. Everyone has his/her own style so if it works for me - but you don't like what I do - or the way I do it - I still go to sleep at night knowing that it works for me. I'm not trying to sell you anything - I'm just offering code that might be helpful to somebody. I'm very sorry if that offends you to the point you must criticize my efforts. If you must pick-pick-pick I hope you feel better now.

I do appreciate the help some have given me in other threads.

BlueThere are two ways to accept criticism, you can take it personally, or you can use it to improve.
1132.

Solve : Remote desktop information through DOS command?

Answer»

Hi,
 I am looking for dos command(s) that return me all the possible information of Remote desktop like its usage, version, license ETC.
Can you please help me?Please explain more clearly what you are asking about. Do you mean information about the remote desktop client version on the same machine? Or a remote machine? Also, you will get much spam if that is your real email address.

Too LATE now... Hi,
Sorry for late response. I was midnight in my timezone.
Yes,I am looking for information about remote desktop client version on the same machine.
Thankyou again. Its my understanding that RDP version is based on WHICHEVER OS version your running... I am not aware of any "updates" to RDP.

XP, Vista, 7, 8, *8.1(?), 10 etc. * Unsure if 8.1 is a different version of RDP than 8.

So knowing what OS version will tell what RDP version.

As far as usage. i am not aware of any LOGGING feature associated with RDP to show use statistics... However one could make an app that works as a launcher/logger for RDP service. So service is off and RDP service is turned on and logged and then turned off when session complete maybe. By use of a NET START TermService instruction locally or a SC \\servername start TermService  remotely.

https://www.windows-commandline.com/start-terminal-services-command-line/

1133.

Solve : xcopy/copy refuses to use long file names?

Answer»

Good evening:

When I use COPY or XCOPY, I can use the long names for the directories using ""s, but when copying using wild card like:

xcopy C:\"Program Files"\"USAPhotoMaps"\"USAPhotoMapsData"\u%1*.*  F:\USAMaps\USAPhotoMapsData\ /y

It uses the short name, which doesn't match the same criteria.

I see the /N switch that says it will force the use of the short name, but leaving it off doesn't use the long name.  Same results with xcopy and copy.

BTW, I have verified that the %1 parameter really contains what I expect.  Also, doing a DIR /x shows the files like u17nnnnnn.ptr with a short name of U10000~1.PTR, so I'm sure I am not misinterpreting the symptoms.

Makes me a little afeared to try the next step which is a wild card DELETE of the same files.

Any ideas?

Windows XP

-dan

My programs don't have bugs, they just develop random features.
Have you tried just one set of "" such as

xcopy "c:\etc f:\etc" /v

and what with the \u - should that be /u  or is it part of the %1:-?

Welcome to the forums.I tried the following two both with and without the /v.  Don't see /v documented in help, but it didn't say invalid switch.  Verbose?

xcopy "C:\Program Files\USAPhotoMaps\USAPhotoMapsData\u%1*.*  F:\USAMaps\USAPhotoMapsData\" /v

xcopy "C:\Program Files\USAPhotoMaps\USAPhotoMapsData\u%1*.*"  "F:\USAMaps\USAPhotoMapsData\" /v

Still uses the short name.

With only one set of quotes like you had it said "invalid path", which kinda makes sense.  I figured you really meant 1 set of quotes around each path.

Yes, the "u" is part of the file name.

Naming convention is xnnymmmmm
x is one of 6 letters.
nn is a number between 10-19 inclusive
y is a constant "y"
mmmmm is a 5 digit sequential number

I want to copy all the files for xnn from one directory to another.

*******************************
WARNING!

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

You don't have to read this if you don't want, but here's the gory details.

I am downloading files from Terraserver using UASPhotoMaps and Terrafetcher.

x  It creates a separate set of files for each image type (B&W photo, Topo and color Urban photo).  For each of those, there are two sets, one for each of the two resolutions.  That's 6 sets, denoted by the six different letters the files begin with.

nn Then, each set is divided into a set for each UTM zone 10-19.

y  Just to keep the 2 numbers apart, I guess.

mmmmm  Then there's a separate file for each row of tiles downloaded.  Several thousand for each zone.  I now have about 80,000 files.  (Actually, for the higher resolutions this can be as much as 8 digits)

When the project progresses, and especially when I create two converted versions (georeferenced .jpgs and geoTiffs) these files will take up WAY more than I can fit on my little 200GB disk, so I need to spread them out to several 500GB drives.  Screwy part is, the programs will only read and D/L from the INSTALLED drive.

SO, I want to be able to copy an entire zone onto the install disk while I work on it.  AND have the option of copying in 2 zones to work between them both.  Then copying one or both back to work another place.  Hence passing the zone as a parameter.  I only showed one statement, but there'll actually be 6 copy statements, one for each of the 6 letters.

If someone doesn't come up with a solution, I may just create a directory for each zone and then just have to LIMIT myself to working on one zone at a time.

-danDusty,

Silly me.  The /v was just not alphabetical (as some others aren't).  v=verify of course.  I was using /y so I wouldn't get prompted for replacing.

Sorry, it's been years SINCE I did anything in DOS.  I keep typing -y for SWITCHES and / for path separator.  But all that time on PC XTs is slowly coming back.

-danMore details:

It's stranger than I thought.

Looking at the dir /x of the files that have been copied for zone 10:

All the files that were copied have EITHER the long name OR the short name starting with u10

Examples:
U10Y82~1   u10y82700.dta
U1884B6~1  u10y82799.dta
U10E99~1  u13y87564.dta

When using the /n switch, it displays the short name while copying.  Without the /n it displays the long name.

Stranger still, when using the /n, it STILL copies ones that don't match.  But it looses the long name when it does, as seen through dir /x or in Windows Explorer.

The original files show in the correct alphabetical order, so I don't think the directory is fried.  But it sure seems weird.

-danSorry - it's been long hard day and I must confess you've got me on that one.

Quote

BTW, I have verified that the %1 parameter really contains what I expect.

Quote
Naming convention is xnnymmmmm
x is one of 6 letters.
nn is a number between 10-19 inclusive
y is a constant "y"
mmmmm is a 5 digit sequential number

I'm kinda puzzled by your use of a single % (percentage sign) which is not a wildcard so doesn't represent any letter/digit in the file name.  Seems to me that U1*.* would copy/xcopy every file in the 'U10ymmmmm' thru 'U19ymmmmm' range.  

However if you have SET 1=something then it's understandable except that you need to use the full %1% (leading and trailing percentage signs) in the filename.

Why does my tired brain keep giving me the message there's something I've missed and that I've just made a complete fool of myself - again:-?

Grrrrrrrr
Quote
Sorry - it's been long hard day and I must confess you've got me on that one.

Quote
BTW, I have verified that the %1 parameter really contains what I expect.

Quote
Naming convention is xnnymmmmm
x is one of 6 letters.
nn is a number between 10-19 inclusive
y is a constant "y"
mmmmm is a 5 digit sequential number

I'm kinda puzzled by your use of a single % (percentage sign) which is not a wildcard so doesn't represent any letter/digit in the file name.  Seems to me that U1*.* would copy/xcopy every file in the 'U10ymmmmm' thru 'U19ymmmmm' range.  

However if you have SET 1=something then it's understandable except that you need to use the full %1% (leading and trailing percentage signs) in the filename.

Why does my tired brain keep giving me the message there's something I've missed and that I've just made a complete fool of myself - again:-?

Grrrrrrrr

I could have sworn I replied to this, but it's not there, so here goes again.

The %1 is parameter 1.  I call the .bat file and pass a number from 10-19 for the zone.

I'm thinking I'll just write something in C, though I bet it'll be much slower since I'll have to call the copy once for each file.

For now, I have just extracted the high resolution B&W photos out and an working on the other types.

I'm glad to see it has you confused as well.  Makes me feel not quite so dumb.

Thanks for you help, Dusty!

-dan

Best and quick solution is to use (long_path_tool)If he comes back...after 10 years i'm sure he'll appreciate it...
1134.

Solve : How to output echo'd info from a for loop?

Answer»

Hello!

Fairly simple problem that I can't figure out. 

I managed to get this far :

Code: [Select]for %F in ("e:\*") do echo %F=:=%~zF
Which does what I WANT.  The =:= is there just so I have something to explode off of when reading this in to a PHP script.  Now I tried using the > filename.txt to direct the output to a file but in the end I would only get the name of the that file "filename.txt" and it's file size.

This will be my one learned thing for the day! 

Thanks for any and all help, super appreciated!

DaveHi 

So what is the result of those commands ?

Code: [Select]for %F in ("e:\*") do echo %F=:=%~zF > e:\File_Size1.txt
and this :

Code: [Select]for %F in ("e:\*") do echo %F=:=%~zF >> e:\File_Size2.txtSorry I didn't respond earlier but yes it seems that second option does work and lists all the files in that directory the first just shows the last file.  Which leads me to BELIEVE it just kept over writing the file every TIME. Ugh!

Thanks for getting me un-stuck!  As you found, a single chevron > overwrites the file while double chevrons append.  I've found it works best to write the BATCH file in such a way that the first file echoed to the file is done with one >, while the rest are echoed with two >>.  That way, I get a new file each time but I still get everything.

You could also just delete the file first, then use >> to do the ECHOING.

1135.

Solve : Use batch file to insert text in a text file after a word i specify??

Answer»

To put it in plain terms guys n gals what i would like to know is if this is possible?

I have say 25 text files that have different information in them but at the bottom there is 2 lines the same in them all and i need to insert a further 2 lines because my database does not add them in while exporting them.

Would it be possible to create a batch file that would allow me to run it and upon running it edit these text files and insert two lines after a specific word which would save me a great deal of time doing it manually.

Any help will be much appreciated and thank you in advance.

Ryanpost example of this txt file and show us where you want to put them  well there is 25 different files all with information like the following:

20091105,20091105,1501-1502
20091112,20091112,1501-1502
20091119,20091119,1501-1502
20091126,20091126,1501-1502
20091203,20091203,1501-1502
20091210,20091210,1501-1502
20091217,20091217,1501-1502
20091224,20091224,1501-1502
]
SCHEDULES BAYS [
]
SCHEDULES CLEANUP
SYS CONFIG 20090427

I want to insert :

SYS DUEGATE 60 05:00
DISPLAY SCHED 00:30 01:30

after CLEANUP but on a new line so it would look like the following:

SCHEDULES CLEANUP
SYS DUEGATE 60 05:00
DISPLAY SCHED 00:30 01:30
SYS CONFIG 20090427

the text at the start is just a few lines from the document there are hundreds of lines. thanks if you can help you would be a LEGEND lol Code: [Select]echo off
setlocal enabledelayedexpansion
set num = 0

for /f "tokens=*" %%a in (file.txt) do (
if !num! lss 12 echo %%a >>output.txt
if !num! EQU 12 set lastline=%%a
set /a num+=1
)

echo.SYS DUEGATE 60 05:00 >>output.txt
echo.DISPLAY SCHED 00:30 01:30 >>output.txt
echo %lastline% >>output.txt

echo.DONE!
pause
this works for me after output.txt is created you can DEL file.txt and rename output.txt to file.txt

PS done fast, i need to sleep if you have Perl and able to use it.
Code: [Select]# perl -i.bak-ne 'print /CLEANUP$/?$_."SYS DUEGATE 60 05:00\nDISPLAY SCHED 00:30 01:30\n":$_' file*
20091105,20091105,1501-1502
20091112,20091112,1501-1502
20091119,20091119,1501-1502
20091126,20091126,1501-1502
20091203,20091203,1501-1502
20091210,20091210,1501-1502
20091217,20091217,1501-1502
20091224,20091224,1501-1502
]
SCHEDULES BAYS [
]
SCHEDULES CLEANUP
SYS DUEGATE 60 05:00
DISPLAY SCHED 00:30 01:30
SYS CONFIG 20090427
1. Create a folder C:\test1
2. Create a folder C:\test2
3. Move your 25 different files to C:\test1
4. Run below batch file
5. You'll get the result in C:\test2

Code: [Select]echo off
set SrcFolder=C:\test1
set DstFolder=C:\test2
for %%a in ("%SrcFolder%\*.txt") do (
  (for /f "tokens=1* delims=:" %%h in ('findstr /n .* "%%a"') do (
    echo.%%i
    if %%h equ 12 (
      echo SYS DUEGATE 60 05:00
      echo DISPLAY SCHED 00:30 01:30
    )
  ))>"%DstFolder%\%%~nxa"
)
guys wow replies were excellent and very fast thanks very much, this forum rocks.

i'll try them all and see which one works best for me but i CANT express how greatful i am to you all this is gonna save me a shed load of time and i can focus that elsewhere.

thank yous so much i'm really greatful Quote from: rytech on April 22, 2009, 06:16:19 AM

guys wow replies were excellent and very fast thanks very much, this forum rocks.

i'll try them all and see which one works best for me but i cant express how greatful i am to you all this is gonna save me a shed load of time and i can focus that elsewhere.

thank yous so much i'm really greatful

quick question to batcher, i noticed equ 12 does that insert the text i want on line 12 cause there is like hundreds of different lines and it is near the end and it is not on the same line anytime, i like the look of yours best as it seems the simplest so COULD you edit it to insert the text after the word i originally specified?

is that possible?if line 12 always have the word CLEANUP, then the batch solution should be ok. Otherwise, need to change it to something more flexible.does my solution work ?  Quote from: rytech on April 22, 2009, 06:22:01 AM
quick question to batcher, i noticed equ 12 does that insert the text i want on line 12 cause there is like hundreds of different lines and it is near the end and it is not on the same line anytime, i like the look of yours best as it seems the simplest so could you edit it to insert the text after the word i originally specified?

is that possible?

Everything is possible. Try this one.

Code: [Select]echo off
set SrcFolder=C:\test1
set DstFolder=C:\test2
for %%a in ("%SrcFolder%\*.txt") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    echo.%%h
    if "%%h" equ "SCHEDULES CLEANUP" (
      echo SYS DUEGATE 60 05:00
      echo DISPLAY SCHED 00:30 01:30
    )
  ))>"%DstFolder%\%%~nxa"
)
Batcher your the man thanks very much buddy Devcom i never tried it mate cause the line number thing you had in yours but batchers done the job and i edited the batch file to delete the un needed folder once it had done it so it's all sorted but i need to know if it is possible to delete some text in the file and replace it, i need to replace the date with the date i am working with rather than the date set in the files as well it was just i forgot about that so i have:

ECHO OFF
set SrcFolder=C:\Test
set DstFolder=C:\Test1
for %%a in ("%SrcFolder%\*.txt") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    echo.%%h
    if "%%h" equ "SYS CONFIG 20090327" (
      echo SYS CONFIG 20090427
    )
  ))>"%DstFolder%\%%~nxa"
)

Where SYS CONFIG 20090327 i want that replaced with SYS CONFIG 20090427, is that possible, this question goes to my man batcher lol or anyone with the knowledge cause i aint got it try to change this:
Code: [Select]    echo.%%h
    if "%%h" equ "SYS CONFIG 20090327" (
      echo SYS CONFIG 20090427
    )to
Code: [Select]    if "%%h" equ "SYS CONFIG 20090327" (
      echo SYS CONFIG 20090427
    ) else (
    echo.%%h
    )
should work devcom sorry to be a bloody pain but it says the system could not find the path specified, here is what i have, can you think of anything that looks wrong?

ECHO OFF
set SrcFolder=c:\test
set DstFolder=C:\test1
for %%a in ("%SrcFolder%\*.txt") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    if "%%h" equ "SYS CONFIG 20090327" (
      echo SYS CONFIG 20090427
    ) else (
    echo.%%h
    )
  ))>"%DstFolder%\%%~nxa"
)

ECHO.
ECHO Done!
ECHO.
PAUSE
CLS
1136.

Solve : finding/moving files?

Answer»

Good Morning

Could someone tell me what the dos cmd is to find all pdf files in all sub directories and copy them to a named folder please.

Thank you

Quote from: widetree on April 20, 2017, 03:59:27 AM

Good Morning

Could someone tell me what the dos cmd is to find all pdf files in all sub directories and copy them to a named folder please.

Thank you
Hi 
Did you mean move or copy them in NEW folder ?To copy pleaseHi 
You can give a try with this batch file : CopyPDF.bat
Just copy and paste this code with your NOTEPAD and save it as CopyPDF.bat and just drag and drop your folder on it.

Code: [Select]echo off
Title Copying All PDF files in folder and its subfolders with drag and drop
Mode con cols=75 lines=3 & color 0E
set "Drag_Dir=%~1"
set "Ext=pdf"
echo(
IF ["%Drag_Dir%"] EQU [""] Goto:Error
set "newFolder=%Drag_Dir%\New_%Ext%_Folder"
Rem Create the new folder to copy all *.pdf on it
If not exist "%newFolder%" md "%newFolder%"
2>nul cd "%newFolder%" && Call :CopyPDFfiles || Goto:Error
EXplorer "%newFolder%"
Exit
::********************************************
:CopyPDFfiles
for /f "delims=" %%I in ('Dir /a-d /b /s "%Drag_Dir%\*.%Ext%"') do (
    Copy /Y "%%I" "%newFolder%"
)
Exit /b
::********************************************
:Error
Mode con cols=75 lines=5 & Color 0C
echo(
ECHO           You must drag and drop a folder on this batch program
ECHO                 to copy all PDF files in new location
Timeout /T 10 /NoBreak >nul
Exit /b
::*****************************************Thank you Hacko.

It created the folder but no pdf's inside it. Quote from: widetree on April 20, 2017, 07:41:51 AM
It created the folder but no pdf's inside it.
Check if your folder and its subfolders contains any pdf files or not !
if the batch file dosen't find any pdf files it create an empty folder named New_PDF_FolderYes that worked beautifully! Thank you very much! Could you possibly tweet the code so I could run this batch file to find pdf's with a name containing the characters "plan"? Quote from: widetree on April 20, 2017, 08:13:16 AM
Yes that worked beautifully! Thank you very much! Could you possibly tweet the code so I could run this batch file to find pdf's with a name containing the characters "plan"?
Here we go 
Code: [Select]echo off
Title Copying All PDF files in folder and its subfolders with drag and drop
Mode con cols=75 lines=3 & color 0E
set "Drag_Dir=%~1"
set "Ext=pdf"
set "Word=plan"
IF ["%Drag_Dir%"] EQU [""] Goto:Error
set "newFolder=%Drag_Dir%\New_%Ext%_Folder"
Rem Create the new folder to copy all *.pdf on it
If not exist "%newFolder%" md "%newFolder%"
2>nul cd "%newFolder%" && Call :CopyPDFfiles || Goto:Error
Explorer "%newFolder%"
Exit
::********************************************
:CopyPDFfiles
for /f "delims=" %%I in ('Dir /a-d /b /s "%Drag_Dir%\*.%Ext%" ^| find /I "%Word%"') do (
Rem find all pdf's with a name containing the characters "plan" and copy them to the newfolder
    Copy /Y "%%I" "%newFolder%"
)
Exit /b
::********************************************
:Error
Mode con cols=75 lines=5 & Color 0C
echo(
ECHO           You must drag and drop a folder on this batch program
ECHO                 to copy all PDF files in new location
Timeout /T 10 /NoBreak >nul
Exit /b
::*****************************************That worked too! Thank you so much! I did not realise so much coding was involved. Quote from: widetree on April 21, 2017, 12:14:51 AM
That worked too! Thank you so much! I did not realise so much coding was involved.
You are welcome dude and don't forget to use the Thanks LINK 
Have a nice day !
1137.

Solve : need to create a batch file to Convert .csv to html?

Answer»

Hi team,

I am try to create a batch file which convert .csv file to html
but the html file is not showing in proper format .

please help to create this script .


also Can be browser a file in batch script .

echo off
setlocal EnableExtensions EnableDelayedExpansion
for /f "tokens=1,* delims=: " %%a in (csv2.csv) do (
set "var=!var!,%%a"
set "var2=!var2!,%%b"
)
>file.html echo %var:~1%
>>file.html echo %var2:~1%
pause

thank you If you want to see it WITHIN a browser window you could FLIP the .csv into a .txt and view it that way. If your going to convert this to a html I would start with prepending HTML tags to the document, then append the .csv contents to that html file and then append the proper HTML closing tags. The .csv content can all be within the Code: [Select]<BODY>  </BODY> tags.Hi 
you should provide a csv file to test it, but anyway,
you can try something LIKE that as example with delimiters ","
CSV2HTML.bat
Code: [Select]echo off
Title Convert csv file to HTML file
if exist data.html del /f /q data.html
call :CreateHTMLtable data.csv data.html
start "" data.html
exit /b
::******************************************************************************************************
:CreateHTMLTable <inputfile> <outputfile>
setlocal
>%2 (
echo ^<!DOCTYPE HTML PUBLIC
echo "-//W3C//DTD HTML 4.01 Transitional//EN"
echo  "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"^>
echo ^<HTML^>
echo ^<HEAD^>
echo ^<META HTTP-EQUIV="Content-Type"
echo CONTENT="text/html; charset=utf-8"^>
echo ^</HEAD^>
echo ^<BODY^>
echo ^<style type="text/css"^>
echo .tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #bcaf91;border-COLLAPSE: collapse;}
echo .tftable th {font-size:12px;background-color:#ded0b0;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;text-align:left;}
echo .tftable tr {background-color:#e9dbbb;}
echo .tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;}
echo .tftable tr:hover {background-color:#ffffff;}
echo ^</style^>
echo ^<table CLASS="tftable" border="1"^>
)

for /f "tokens=1,2 delims=," %%a in (%1) do (
>>%2 echo ^<tr^>^<td^>%%a^</td^>^<td^>%%b^</td^>^</tr^>
)

>>%2 (
echo ^</table^>
echo ^</BODY^>
echo ^</HTML^>
)
::******************************************************************************************************
Here is another way to set what is your delimiters in your csv file :
Code: [Select]echo off
Title Convert csv file to HTML file
Rem you set what is your delimters in your csv file
set "delims=,"
if exist data.html del /f /q data.html
call :CreateHTMLtable data.csv data.html
start "" data.html
exit /b
::******************************************************************************************************
:CreateHTMLTable <inputfile> <outputfile>
setlocal
(
echo ^<!DOCTYPE HTML PUBLIC
echo "-//W3C//DTD HTML 4.01 Transitional//EN"
echo  "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"^>
echo ^<HTML^>
echo ^<HEAD^>
echo ^<META HTTP-EQUIV="Content-Type"
echo CONTENT="text/html; charset=utf-8"^>
echo ^</HEAD^>
echo ^<BODY^>
echo ^<style type="text/css"^>
echo .tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #bcaf91;border-collapse: collapse;}
echo .tftable th {font-size:12px;background-color:#ded0b0;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;text-align:left;}
echo .tftable tr {background-color:#e9dbbb;}
echo .tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;}
echo .tftable tr:hover {background-color:#ffffff;}
echo ^</style^>
echo ^<table class="tftable" border="1"^>
)>%2

for /f "tokens=1,2 delims=%delims%" %%a in (%1) do (
echo ^<tr^>^<td^>%%a^</td^>^<td^>%%b^</td^>^</tr^>
)>>%2

(
echo ^</table^>
echo ^</BODY^>
echo ^</HTML^>
)>>%2
::******************************************************************************************************This an update version 
CSV2HTML.bat
Code: [Select]echo off
Title Convert csv file to HTML file
Rem Set what is your delimiters in your csv file like [,] [;] [:] [|] or [tab]
set "delims=:"
Rem Set the name of the CSV file into a variable
set "CSV_File=data.csv"
Rem Set the name of the HTML output file from CSV file into variable
for %%a in ("%CSV_File%") do set "HTML_File=%%~na.html"
if exist "%HTML_File%" del /f /q "%HTML_File%"
Call :CreateHTMLtable "%CSV_File%" "%HTML_File%"
start "" "%HTML_File%"
exit /b
::******************************************************************************************************
:CreateHTMLTable <inputfile> <outputfile>
setlocal
(
echo ^<!DOCTYPE HTML PUBLIC
echo "-//W3C//DTD HTML 4.01 Transitional//EN"
echo  "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"^>
echo ^<HTML^>
echo ^<HEAD^>
echo ^<META HTTP-EQUIV="Content-Type"
echo CONTENT="text/html; charset=utf-8"^>
echo ^</HEAD^>
echo ^<BODY^>
echo ^<style type="text/css"^>
echo .tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #bcaf91;border-collapse: collapse;}
echo .tftable th {font-size:12px;background-color:#ded0b0;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;text-align:center;}
echo .tftable tr {background-color:#e9dbbb;}
echo .tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91; text-align:center;}
echo .tftable tr:hover {background-color:#ffffff;}
echo ^</style^>
echo ^<center^>^<table class="tftable" border="1"^>
)>%2

setlocal enabledelayedexpansion
for /F "delims=" %%A in ('Type "%~1"') do (
set "var=%%A"
set "var=!var:&=&amp;!"
set "var=!var:<=&lt;!"
set "var=!var:>=&gt;!"
set "var=!var:%delims%=</td><td>!"
echo ^<tr^>^<td^>!var!^</td^>^</tr^>
)>>%2

(
echo ^</table^>^</center^>
echo ^</BODY^>
echo ^</HTML^>
)>>%2
endlocal
::******************************************************************************************************Hi 
This is a new version that can be used with a drag and drop a csv file over the batch file to be converted in HTML Table.
CSV2HTML.bat
Code: [Select]echo off
Mode con cols=70 lines=3 & color 0E
Title Convert csv file to HTML file
Rem Set what is your delimiters in your csv file like [,] [;] [|]
set delims="," ";" "|"
set "CSV_File=%~1"
IF ["%CSV_File%"] EQU [""] Goto:Error
Rem Set the name of the HTML output file from CSV file into variable
for /f "usebackq delims=" %%a in (`echo "%CSV_File%"`) do ( set "HTML_File=%%~na.html")
if exist "%HTML_File%" del /f /q "%HTML_File%"
echo(
echo         Converting to "%HTML_File%" is in progress ...
Timeout /T 2 /nobreak>nul
Call :CreateHTMLtable "%CSV_File%" "%HTML_File%"
start "" "%HTML_File%"
exit /b
::******************************************************************************************************
:CreateHTMLTable <inputfile> <outputfile>
setlocal
(
echo ^<!DOCTYPE HTML PUBLIC
echo "-//W3C//DTD HTML 4.01 Transitional//EN"
echo  "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"^>
echo ^<HTML^>
echo ^<HEAD^>
echo ^<META HTTP-EQUIV="Content-Type"
echo CONTENT="text/html; charset=utf-8"^>
echo ^</HEAD^>
echo ^<BODY^>
echo ^<style type="text/css"^>
echo .tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #bcaf91;border-collapse: collapse;}
echo .tftable th {font-size:12px;background-color:#ded0b0;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91;text-align:center;}
echo .tftable tr {background-color:#e9dbbb;}
echo .tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #bcaf91; text-align:center;}
echo .tftable tr:hover {background-color:#ffffff;}
echo ^</style^>
echo ^<center^>^<table class="tftable" border="1"^>
)>%2

setlocal enabledelayedexpansion
for /F "delims=" %%A in ('Type "%~1"') do (
set "var=%%A"
set "var=!var:&=&amp;!"
set "var=!var:<=&lt;!"
set "var=!var:>=&gt;!"
for %%a in (%delims%) do (
set "var=!var:%%~a=</td><td>!"
)
echo ^<tr^>^<td^>!var!^</td^>^</tr^>
)>>%2

(
echo ^</table^>^</center^>
echo ^</BODY^>
echo ^</HTML^>
)>>%2
endlocal
exit /b
::******************************************************************************************************
:Error
Color 0C
echo.
ECHO    You must drag and drop a .csv file over this batch program !
Timeout /T 4 /NoBreak >nul
Exit

1138.

Solve : Unable to copy files containing html tags after adding text inside it.?

Answer»

Hi everyone,
Thanks for this siteit helped me a lot in doing my project but i am facing some issue,HOPE you can suggest me how to get out of this...

As part of a project I need to add text to the middle of many files using batch scripting. I am able to add the text successfully, but after copying the files to a new location I noticed that the HTML tags are missing. I only have this problem in Windows Server 2012/2008; in Windows 7 the HTML tags remain.

My Code snippet:
echo off

set SrcFolder=C:\Users\emlfilessample
set DstFolder=C:\Users\output

FOR %%f in (%SrcFolder%*.EML) do (
 (FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ %%f"`) do (
  SETLOCAL EnabledDelayedExpansion
  set "var=%%a"
   set "var=!var:*:=!"
   if "!var:~0,10" == "x-globalre" (
   echo X-SUBTYPE=RETURES
 )
 echo(!var!
 ENDLOCAL
)) >> "%DstFolder%\%%~nxf"
)


 **SAMPLE input eml:**
   Date Mon,20 mar 2017
   From:[email protected]
   To:[email protected]
   Message-ID:<10091223>
    Subject:Symphony
   x-globalrelay-MsgType: XXXX
   x-StreamType:xxxx
   x-contentstartdate:XXX
 
     Message ID:sm9atRNTnMA=Yay1R0QgoH..............

After executing my script in Server 2012 I am able to successfully inject the REQUIRED text in the middle, but as I said the HTML tags are missing:

 **Sample output eml:**
   Date Mon,20 mar 2017
   From:[email protected]
   To:[email protected]
   Message-ID:<10091223>
    Subject:Symphony
   echo X-SUBTYPE=RETURES
   x-globalrelay-MsgType: XXXX
   x-StreamType:xxxx
   x-contentstartdate:XXX
    < Yay1R0QgoH..............
 
as shown above after executing the script the html tags at the begining are missing i am not able to find out why....can any one help me with thisHi 
You GOT an answer here, so check it !

1139.

Solve : remove lines in txt files?

Answer»

Windows 7

I have a number of folders each containing a lot of text files.  In each file I want to REMOVE lines up to and including a line starting with 'xxxxxxx'.  I would prefer that the edited files be saved in a folder other than the original folder, i.e. I don't want to lose the original files, although I do have backup copies of the files.

Ideally I would prefer a freeware utility with a GUI. I tried to find something, but everything I found was overkill and/or quite expensive for occasional use.  FWIW : a friend recently RECOMMENDED Bulk Renamer Utility (BRU) to do some tricky renaming of the text files, which I've done.  If someone knows of a freeware utility of similar calibre to BRU to do the bulk editing, that would be ideal. 

Otherwise a batch command file would be OK. 

I've never been any good at writing any sort of computer code. How anyone can comprehend, let alone type, so-called 'regular  expressions' always ASTONISHES me.  But I am pretty good with cut and paste 

Thanks - PhilD   Addenda

If the 'xxxxxxxx' string isn't present

  • a message might be useful,
  • the input file should remain in place,
  • and if the output files are being written to a different folder (preferred) then nothing should written.
PhilDYou should be more explicit if you show us with an example file to explain more your aim !Welcome to the DOS section...Hint:...get used to it.I wasn't sure where to post this, but I anticipated a batch script solution so I thought DOS Box - that'll do.

Sample file attached - can't attach a real one, not my property and contains private data.  There are thousands of files, they are not large files, 30-1000KB each.   

In each text file in an Input folder I want to delete everything down the line that starts with say Purpose: and write the edited file to an Output folder, if Purpose: is not found write the file to an Exceptions folder.

So a command might look something  like

Code: [Select]EditTextFiles -i="d:\textdata\first set of files" -s="Purpose:", -o="d:\textdata\first set of files\edited", -e="d:\textdata\first set of files\exceptions"

where

     -i is the input directory/folder;
     -s is the search string;
     -o is the output directory/folder;
     -e is the exceptions directory/folder.


The person who 'owns' the data is a competent computer user, but not a computer geek, hence a preference for a GUI based tool.  But a batch script will do.

PhilD



[attachment deleted by admin to conserve space]Once you have a thing that works, you can 'decorate' it with Vb Script.
You can use Visual Basic to create VB Scripts that will run with batch files.
You might look at this:
https://social.msdn.microsoft.com/Forums/en-US/6cf20733-75c4-4018-81dc-22369020e492/creating-a-gui-with-visual-basic?forum=Vsexpressvb
Also this:
http://www.instructables.com/id/How-to-Make-a-message-box-using-VBScript/
And:
https://community.spiceworks.com/topic/93619-vbscript-to-gui-or-to-visual-basic

Of course, none of the above are specific to what you are doing.  But almost anything you do in batch cam can  made into a GUI program.A VB Script can INVOKE a command line program and get the results sent to a file.

Some users hate using anything related to Visual Basic. Nevertheless, Visual Basic and is offspring have done and still  do a lot of work in the IT industry. 

https://en.wikipedia.org/wiki/Visual_Basic
Quote
On April 8, 2008, Microsoft stopped supporting Visual Basic 6.0 IDE.
...
In 2014, some software developers still preferred Visual Basic 6.0 over its successor, Visual Basic .NET.[3][9] In 2014 some developers lobbied for a new version of Visual Basic 6.0.[10][11][12][13] In 2016, Visual Basic 6.0 won the technical impact award at The 19TH Annual D.I.C.E. Awards.[14][15][16] A dialect of Visual Basic, Visual Basic for Applications (VBA), is used as a macro or scripting language within several Microsoft applications, including Microsoft Office.[17]
Some early versions of Visual Basic are easy to learn and are compatible with current versions of Windows. Here is a link for the free 2008 version:
http://www.freewarefiles.com/Microsoft-Visual-Basic-Express-Edition_program_17931.html   

Quote from: Geek-9pm on April 25, 2017, 08:29:55 PM
Once you have a thing that works, you can 'decorate' it with Vb Script.
Thanks - but I'm a minimalist - less is better, least is best.  This is a short term need for dealing with the thousands of archived text files. The ongoing updates won't come from text files, they will go directly into the database as LOB transactions.

For the job at hand a batch file solution will perfectly adequate.

PhilD


OK. You are the one who keeps adding things.
But you fest said:
Quote
  In each file I want to remove lines up to and including a line starting with 'xxxxxxx'. 
That is almost trivia. The pseudo code is:

open file.
begin loop
  read a line
  If line starts with  'xxxxxxx' exit loop
  write line to output
end loop
close

Is that what you want?


Quote from: Geek-9pm on April 25, 2017, 11:11:15 PM
OK. You are the one who keeps adding things.
But you fest said:That is almost trivia. The pseudo code is:

open file.
begin loop
  read a line
  If line starts with  'xxxxxxx' exit loop
  write line to output
end loop
close

Is that what you want?
What I wrote was
Quote from: PhilD on April 25, 2017, 01:18:00 PM
I have a number of folders each containing a lot of text files.  In each file I want to remove lines up to and including a line starting with 'xxxxxxx'. 

I did add a post because I forgot the exception condition of the xxxxxxx not being found

I provided a sample and clarification as requested by Hackoo.

I responded Geek_9s suggestion that I write something in Basic. 

If its batch file I want to be able specify the input folder, the search string, the output folder and the exceptions folder in a command line, in essence I don't want those things hard coded in the batch file.

So assuming xxxxxx is 'Purpose:" for file shown in the attachment I do not want lines 1 to  15 to be written, the output would consist of lines 16 until the end of file

If the xxxxxx isn't found copy the file to an exceptions folder

And I want it to operate on every .txt file in the input folder.

I appreciate it is not very hard for you, but at 83 I find coding hard. 

Thanks PhilD









[attachment deleted by admin to conserve space]You are 83? Now I understand why you want it simple.
I am 78 and get tired very easy. For me, it works best if I can divide things into little parts. Tomorrow I will look at this again and if nobody has given you a batch file, I will try to do something in a script.   
Quote from: Geek-9pm on April 26, 2017, 01:05:55 AM
You are 83? Now I understand why you want it simple.
I am 78 and get tired very easy. For me, it works best if I can divide things into little parts. Tomorrow I will look at this again and if nobody has given you a batch file, I will try to do something in a script.   
Thanks pal - had mild stroke a few years ago, it zapped any coding skills I ever had. 

Hi 
I made this script just for testing for one file ! and you should confirm me if this what you want for one file or not ?
Code: [Select]echo off
Set "Stop_String=Purpose"
Set "File=Sample.txt"
Set "OutPutFile=OutPutFile.txt"
if exist "%OutPutFile%" Del "%OutPutFile%"
set /A "Count=0"

For /f "tokens=1 delims=:" %%A in ('findstr /I /N "%Stop_String%" "%File%"') Do (
Set /a "Count=%%A"
)
echo We found the string "%Stop_String%" at line number %Count%
pause & Cls

For /f "skip=%Count% delims=*" %%a in ('Type "%File%"') do (
echo %%a 
echo %%a >> "%OutPutFile%"
)
echo.
Echo Hit any key to open the output file ...
pause>nul
Start "" "%OutPutFile%" & exit Quote from: Hackoo on April 26, 2017, 01:46:16 AM
Hi 
I made this script just for testing for one file ! and you should confirm me if this what you want for one file or not ?
Thanks a lot Hackoo

Yeah it finally worked - my blunder

I didn't copy all the code, I don't see many SMF forums

PD



Hi 
This an update version with Browse for folder 
Just give a try and tell me the result 
Code: [Select]echo off
Title Search for files and remove lines in text files
mode con cols=75 lines=5 & Color 0A
REM We set the variable Folder with the function Browse4Folder
Call :Browse4Folder "Choose source folder to scan for files" "c:\scripts"
Set "Folder=%Location%"
Rem if the variable %Folder% have a trailing back slash, we remove it !
IF %Folder:~-1%==\ SET "Folder=%Folder:~0,-1%"
If "%errorlevel%" EQU "0" (
echo( & echo(
echo You choose this folder "%Folder%"
Timeout /T 2 /nobreak>nul
) else (
echo( & echo(
echo  "%Folder%"
Timeout /T 2 /nobreak>nul & Exit
)
Set "Stop_String=Purpose"
Set "Edited_Files=%HomeDrive%\Edited_Files"
Set "Exceptions_Folder=%HomeDrive%\Exceptions"
If not exist "%Edited_Files%" MD "%Edited_Files%"
If not exist "%Exceptions_Folder%" MD "%Exceptions_Folder%"
SetLocal EnableDelayedExpansion
for /f "delims=" %%f in ('Dir /b /s "%Folder%\*.txt"') Do (
Cls
echo.
set /A "Count=0"
set "InputFile=%%~dpFf"
findstr /I /C:"%Stop_String%" "!InputFile!" >nul 2>&1
If "!ErrorLevel!" EQU "0" (
Call :Counting "%Stop_String%" "!InputFile!"
echo We found the string "%Stop_String%" at line number !Count! on "!InputFile!"
Timeout /T 4 /nobreak>nul
Set "OutPutFile=%Edited_Files%\%%~nf_edited.txt"
if exist "!OutPutFile!" Del "!OutPutFile!"
Call :Write2File "!InputFile!" "!OutPutFile!"
) else (
Call :Copyfiles "!InputFile!" "!Exceptions_Folder!"
)
)
Explorer "%Edited_Files%" & exit
::********************************************************************
:Counting <Stop_String> <InputFile>
For /f "tokens=1 delims=:" %%A in ('findstr /I /N "%~1" "%~2"') Do (
Set /a "Count=%%A"
)
exit /b
::********************************************************************
:Write2File <InputFile> <OutPutFile>
For /f "skip=%Count% delims=*" %%a in ('Type "%~1"') do (
echo %%a >> "%~2"
)
exit /b
::********************************************************************
:Browse4Folder
set Location=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
(
    echo set shell=WScript.CreateObject("Shell.Application"^)
    echo set f=shell.BrowseForFolder(0,"%~1",0,"%~2"^)
    echo if typename(f^)="Nothing" Then
    echo wscript.echo "set Location=Dialog Cancelled"
    echo WScript.Quit(1^)
    echo end if
    echo set fs=f.Items(^):set fi=fs.Item(^)
    echo p=fi.Path:wscript.echo "set Location=" ^& p
)>%vbs%
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del /f /q %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
goto :eof
::********************************************************************
:Copyfiles <Source> <Target>
Copy /Y "%~1" "%~2" >nul 2>&1
goto :eof
::******************************************************************** Quote from: Hackoo on April 26, 2017, 11:56:10 AM
Hi 
This an update version with Browse for folder 
Just give a try and tell me the result 
Hi Hakoo - I'm on to it  - Thanks * 80

I'll be back soon as possible








1140.

Solve : Downloading video from youtube using VLC with the command line ??

Answer»

Hi 
I'm making this batch script to download a video in MP4 from youtube using VLC with the command line. and it works fine for me.
VLC_Youtube_Downloader.bat
Code: [Select]echo off
REM Downloading a video from youtube using VLC with the command line by (c) Hackoo 2017
Title Si Lemhaf - Kharrej Legrinta Elli Fik by (c) Hackoo 2017
mode con:cols=65 lines=3 & COLOR 0E
Taskkill /IM "vlc.exe" /F >nul 2>&1
echo.
echo     Please wait a while ... The download is in progress ...
SET Title=Si Lemhaf - Kharrej Legrinta Elli Fik by (c) Hackoo 2017
set "VLC_URL=http://www.videolan.org/vlc/download-windows.html"
set "URL=https://www.youtube.com/watch?v=KDI1C27zEC0"
set "File=SiLmehaf.mp4"
IF /I "%PROCESSOR_ARCHITECTURE%"=="x86" (
        Set "vlc=%ProgramFiles%\VideoLAN\VLC\vlc.exe"
    ) ELSE (
        Set "vlc=%ProgramFiles(x86)%\VideoLAN\VLC\vlc.exe"
)

If Not Exist "%vlc%" (
Cls & COLOR 0C
echo.
Echo       "The VLC program is not installed on your system"
TimeOut /T 5 /NoBreak>nul
Start "" %VLC_URL%
Exit
)

"%vlc%" -vvv "%URL%" --qt-start-minimized --qt-notification=0 --sout=#transcode{vcodec="h264",vb="512",fps="23.97",scale="1",acodec="mpga",ab="128","channels=2",samplerate="44100"}:standard{access="file",mux=mp4,dst=%File%} vlc://QUIT"
REM Starting the video in fullscreen with VLC
Start "" "%vlc%" -f --meta-title="%Title%" %File% But, my problem is why some URLs from Youtube dosen't work ?
like this ONE :

https://www.youtube.com/watch?v=TGtWWb9emYI

I got this error from VLC program
 
Can not recognize the format of the input media
Lots of this in vlc log for that problem video
Code: [Select]http error: error: HTTP/1.1 403 Forbidden Quote from: Salmon Trout on April 18, 2017, 01:23:23 PM

Lots of this in vlc log for that problem video
Code: [Select]http error: error: HTTP/1.1 403 Forbidden
So, did you think that error is coming with a copyright PROTECTED url from youtube ?Could be.
Yepper...
1141.

Solve : batch for using 2 txt files?

Answer»

I am trying to make a batch FILE which will take a comand line from text file and computer name to execute command.
But all what I succed is to take text from first file.

In first.txt I have this line
first.txt
copy /Y \\server1\USERS\%computername%\john\deltmp.txt c:\logs\deltmp.txt

copy.bat
Echo %computername%>>C:\Users\Admin\test\computername.txt
for /f "delims=" %%a in (C:\Users\Admin\test\first.txt) do %%a


When I execute copy.bat I get error
The system cannot find the path specified.
        0 file(s) copied.

because variable %computername% is not recognised from first.txt file
how to read computername so batch will copy that file.
I have CREATED a file computername.txt to read from that file but don't know how to implement that in batch.

And I need it separately batch and first.txt file, because first.txt changes as neededI found a solution with fart
https://sourceforge.net/projects/fart-it/
small program for find and replace Glad you found the answer that WORKS for you.
The fart.exe is a program based on UNIX stuff. It is like grep, a standard UNIX utility.

Windows users might prefer to use Powershell instead.
Look at this post about fart:
HTTP://lifehacker.com/354546/find-and-replace-text-with-fart
Notice the third comment:
Quote

why waste time on this when you got powershell?
to do a search:
select-string {pattern} {filename}
to do a replace:
$content = get-content {filename}
$content -creplace "searchtext","replacetext" | set-content {filename}
regular expressions are supported in search patterns.
you do this and so much more. Powershell rules.
Powershell Tutorials are available.
https://mva.microsoft.com/en-us/training-courses/getting-started-with-powershell-3-0-jump-start-8276
1142.

Solve : find files older than 7 days and send email?

Answer»

I need a simple batch to find files which are older than 7 days.
if there is no file older than 7 days than email me.
for email I use simple command LINE software

bmail -s mail.mailserver.com -f %username%mailserver.com -t [email protected] -h -a "Archives missing" -b "" -m path.TXT"

In file path.txt are full paths to users archive folder.

I tried with 2 batch files but not working

Code: [Select]forfiles /P ".\logfiles" /S /M *.txt /D -7 /C "START /w mail.bat"

1143.

Solve : command line to restart script.bat ??

Answer»

Hi, all i want is to add a NEW line to script.bat, so when when my tool disconnect or receive the word ''error connection'' repeating more then 10 times then ''script.bat''  must restart itself.I will also POST the script if there is anyone who wants to help me
thank you

P.S.

I used a paid tool called '' AlwaysUP'' but when script.bat is disconnected does not re-connect after 5 min (i set waiting time 5 min. then reconnect )but does not work, i don't know how to solve thisYou can add your script batch and use the BBCode # [ code][/ code]I set AlwaysUP application to restart this ''script.bat(wich work with Ncrack)'', just 5 minutes after the death of the process with no effect,so when this process dies?Is about RDP i have my own 2 rdp's and i do this for educational porpose. So Ncrack script process dies on my 1'st RDP when my 2'nd rdp is restarted and then after 1-5 min my 2'nd rdp is UP again but my script is from 1'st rdp is unable to RECOVER the process,how to solve this?need to add a new line or someone who knows how to work with AlwaysUP aplication. This is the bat script here:  Code: [Select]https://pastebin.com/ip3sKkAA
Can anyone take a look please?I tried to find help in diferrent PLACES with no succes,thank you
team viewer? Quote from: karlosss on May 13, 2017, 06:35:57 AM

script.bat(wich work with Ncrack)
Ncrack is a high-speed network authentication cracking tool. Also, like we're sure going to go to your link for this!
Topic Closed...
1144.

Solve : I need a batch or a command line to restart the ''process?

Answer»

I need a batch or a command line to restart the ''process'' 2 minutes after the process is over
thank youHi 
This an example TRYING to check if the process "Calc.exe" is running or not
You can custom the variable %Delay% in your MainLoop
I choose Delay=10 secondes, so for your case you can modify it to 2 minutes=120 secondes
Code: [Select]Set "Delay=120"
and the whole code is like this one :

Code: [Select]echo off
mode con cols=50 lines=4
Set "MyProcess=calc.exe"
Title Check Running Process "%MyProcess%" and Run it if not
REM Delay in secondes
set Delay=10
:MainLoop
cls
Tasklist /FI "IMAGENAME eq %MyProcess%" | find /I "%MyProcess%">NUL && (
cls
echo( & Color 9A
echo         PROCESS "%MyProcess%" IS RUNNING !
)||(
cls
echo( & Color 4C
echo        PROCESS "%MyProcess%" IS NOT RUNNING !
echo           Trying to run "%MyProcess%"
TIMEOUT /T 2 /nobreak>nul
Start "" "%MyProcess%" & Goto MainLoop
)
Timeout /T %Delay% /nobreak>nul
Goto MainLoopmm my process works with AlwaysUP ''as system'' so u can't find '' mytool.exe'' in the processes tab, but maybe works ,thanks Quote from: karlosss on May 14, 2017, 04:53:30 AM

mm my process works with AlwaysUP ''as system'' so u can't find '' mytool.exe'' in the processes tab, but maybe works ,thanks
If this batch dos not work in your case, i will try to write you a vbscript instead
So what did you thing ?What do i think?I radiate of happiness u read the PM i sent to you?u saw the script?restarting and waiting time i need only for that script,can u integrate that command lines inside that script?So when my tool stops need to restart after 5 min. i tried to scheduler with AlwaysUP (This is important:wich runs ''as system'') but no succes maybe need to add some new lines to that script, i don't know so plz take a look,thank you!Ok, this vbscript show you how we can monitor some process if there aren't running like iexplore.exe , notepad.exe, and calc.exe
Check+RunApp.vbs
Code: [Select]Option Explicit
If AppPrevInstance() Then 
WScript.Echo "Instance already running" 
WScript.Quit 
Else 
Do 
Call Main(Array("%ProgramFiles%\Internet Explorer\iexplore","%windir%\system32\calc.exe","%windir%\system32\notepad.exe"))
'Pause 2 minutes
Call Pause(2) 
Loop 
End If 

Sub Main(colProcessPaths) 
Dim ProcessPath 

For Each ProcessPath In colProcessPaths 
CheckProcess(ProcessPath) 
NEXT 
End Sub 

Sub CheckProcess(ProcessPath) 
Dim ProcessName : ProcessName = StripProcPath(ProcessPath) 
msgbox ProcessPath &vbcr& CommandLineLike(ProcessName) &vbcr& CommandLineLike("cmd /c " & chr(34) & ProcessPath & chr(34))
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2") 
With .ExecQuery("SELECT * FROM Win32_Process WHERE Name LIKE " & CommandLineLike(ProcessName) & " OR Commandline LIKE " &  CommandLineLike("cmd /c " & chr(34) & ProcessPath & chr(34))) 
If .Count = 0 Then   
With CreateObject("WScript.Shell")   
.Run DblQuote(ProcessPath) 
End With 
Else   
EXIT Sub   
End if 
End With 
End With 
End Sub 

Function AppPrevInstance() 
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2") 
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptName)) 
AppPrevInstance = (.Count > 1) 
End With 
End With 
End Function 

Sub Pause(Minutes)   
Wscript.Sleep(Minutes*1000*60)   
End Sub 

Function StripProcPath(ProcessPath) 
Dim arrStr : arrStr = Split(ProcessPath, "\") 
StripProcPath = arrStr(UBound(arrStr)) 
End Function 

Function CommandLineLike(ProcessPath) 
ProcessPath = Replace(ProcessPath, "\", "\\") 
CommandLineLike = "'%" & ProcessPath & "%'" 
End Function

Function DblQuote(str) 
DblQuote = chr(34) & str & chr(34)   
End FunctionFor your case i will try to take a look on it or i will advise you where you can ask this kind of question, because i don't know it for the moment how your program work ?can u come now for 1 min with team viewer? u will understand imediatelly how the mechanism work or i can make a video and show you the steps,but with team viewer will much faster and easyi made a change i tried to run my .bat script but opens fast and then crushing

Code: [Select]Option Explicit
If AppPrevInstance() Then 
 WScript.Echo "Instance already running" 
 WScript.Quit 
Else 
 Do 
  Call Main(Array("C:\Windows\windefender\ncrack-autorunner.bat"))
  'Pause 2 minutes
  Call Pause(2) 
 Loop 
End If 

Sub Main(colProcessPaths) 
 Dim ProcessPath 
 
 For Each ProcessPath In colProcessPaths 
  CheckProcess(ProcessPath) 
 Next 
End Sub 

Sub CheckProcess(ProcessPath) 
 Dim ProcessName : ProcessName = StripProcPath(ProcessPath) 
 msgbox ProcessPath &vbcr& CommandLineLike(ProcessName) &vbcr& CommandLineLike("cmd /c " & chr(34) & ProcessPath & chr(34))
 With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2") 
  With .ExecQuery("SELECT * FROM Win32_Process WHERE Name LIKE " & CommandLineLike(ProcessName) & " OR Commandline LIKE " &  CommandLineLike("cmd /c " & chr(34) & ProcessPath & chr(34))) 
   If .Count = 0 Then   
    With CreateObject("WScript.Shell")   
     .Run DblQuote(ProcessPath) 
    End With 
   Else   
    Exit Sub   
   End if 
  End With 
 End With 
End Sub 

Function AppPrevInstance() 
 With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2") 
  With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptName)) 
   AppPrevInstance = (.Count > 1) 
  End With 
 End With 
End Function 

Sub Pause(Minutes)   
 Wscript.Sleep(Minutes*1000*60)   
End Sub 

Function StripProcPath(ProcessPath) 
 Dim arrStr : arrStr = Split(ProcessPath, "\") 
 StripProcPath = arrStr(UBound(arrStr)) 
End Function 

Function CommandLineLike(ProcessPath) 
 ProcessPath = Replace(ProcessPath, "\", "\\") 
 CommandLineLike = "'%" & ProcessPath & "%'" 
End Function

Function DblQuote(str) 
 DblQuote = chr(34) & str & chr(34)   
End Function
1145.

Solve : batch for find and start batch where it is located?

Answer»

I have fev batch files in differend folders and it works as they should when I run it manually.
But I like to create batch to find and start those batch files where they are.
I tried this script but problem is because it finds batch files and it EXECUTE in the same folder as this script, but that is wrong.
Batch which are find must be executed where they are.
Can someone help me with this please?

Code: [Select]for /f "delims=|" %%a in ('dir /B /S new_sendmail1.bat') do call "%%a"I forget to write that batch files which must be executedn by this master batch have relative paths, because of idfferend names of some folders where they are stored, but LAST folder where they are stored is the same for all batch files, like this. I didn't use full paths because folders like that are all together AROUND 100.
d:\users\george\files\logs\new_sendmail1.bat
d:\users\mike\files\logs\new_sendmail1.bat
d:\users\joe\files\logs\new_sendmail1.batThe CD command and the %cd% variables are useful things to know about. In the FOR command you can use the CD command to make each folder where a batch was found, in turn, the current directory, and thus execute from there. You can get the batch path by using the standard FOR variable modifers ~d and ~p.

Here is the master.bat file that runs the individual user batch scripts
I PUT it in d:\users


echo off
echo Starting master.bat
Echo I am master.bat
echo I am stored in:    %~dp0
echo I am running from: %cd%
echo Running individual user batches...
set thisfolder=%cd%
for /f "delims=|" %%a in ('dir /B /S new_sendmail1.bat') do cd "%%~dpa" & call "%%a"
cd "%thisfolder%"
echo Back in master.bat
echo Back in folder:    %cd%
echo Ended master.bat
pause

This is my dummy new_sendmail1.bat file
identical copies stored in d:\users\george, d:\users\mike, and d:\users\joe


echo off
echo This is new_sendmail1.bat
echo I am stored in:    %~dp0
echo I am running from: %cd%
echo Here's the proof...
dir | find "Directory of"
echo exiting...

This is the output I got

Starting master.bat
I am master.bat
I am stored in:    D:\users\
I am running from: D:\users
Running individual user batches...
This is new_sendmail1.bat
I am stored in:    D:\users\george\
I am running from: D:\users\george
Here's the proof...
 Directory of D:\users\george
exiting...
This is new_sendmail1.bat
I am stored in:    D:\users\joe\
I am running from: D:\users\joe
Here's the proof...
 Directory of D:\users\joe
exiting...
This is new_sendmail1.bat
I am stored in:    D:\users\mike\
I am running from: D:\users\mike
Here's the proof...
 Directory of D:\users\mike
exiting...
Back in master.bat
Back in folder:    D:\users
Ended master.bat
Press any key to continue . . .




Thank you!

1146.

Solve : dir on comand prompt?

Answer»

Hi,
I WOULD like list all directories, subdirectories and files as well as the last access date, time and filesize of the HDD recursive in a text file.
how can i do this?

sample:
06.05.2017  10:41          4.204.274    C:\Test\test.exe
14.09.2015  15:32               24.068    C:\Test1\Sample1\test.txt
22.07.2016  06:55      114.204.158    C:\Test2\Sample1\test.jpg
...
...
or
C:\Test\test.exe                         4.204.274     06.05.2017  10:41   
C:\Test1\Sample1\test.txt               24.068    14.09.2015  15:32
C:\Test2\Sample1\test.jpg     114.204.158    22.07.2016   06:55
...
...


I have try it with  dir commad but i can not use correct the parameter  for this output like the sampe.

thanks for your helpHi 
You should take a LOOK at this link ==> https://ss64.com/nt/dir.html
This an example to show you how to list folders and files in your temporary folder :
List_Foders_Files.bat
CODE: [Select]echo off
Set "MasterFolder=%Temp%"
set "TmpFile=%TMP%\%~n0.txt"
set "LogFile=List_Folders_Files.txt"
Dir %MasterFolder% /A /R /S /O:S /T:A > "%TmpFile%"
CMD /U /C Type "%TmpFile%" > "%LogFile%"
Start "" "%LogFile%"

1147.

Solve : Get rid of flicker of echo display?

Answer»

Put this together to log only failed pings with request TIME out. But was playing around with a way to have the output showing and not flickering, but also I dont want to affect how fast this runs either. I know that I could put a sleep condition before the goto to make it display longer before refresh. I sized the shell window down to only show the

Quote

Ping of Device Was Successful
On Thu 04/27/2017 at 9:31:07.84
Ping Logger V2.0 Running...

And this way you dont SEE multiples of each test scrolling. I tried of CLS, but it makes the output ALMOST hidden with constant flicker. Also tried a bunch of echos as a refresh method instead of clear screen but then the output looks like an older TV with the rolling of the PICTURE. I have avoided use of sleep because I want to avoid slowing down the batch if possible to get as precise log data.  Maybe its just the nature of the beast to have the fast execution of this that it will flicker. I guess I am just a perfectionist in that this does as intended, but I guess curious if there is a method that can be implemented that gets rid of flicker and  shows the date and time of each test loop and condition. 

By the way 127.0.0.1 is just for testing purposes. The actual IP address will be entered and saved to this for each IP address to be logged. You can change it to some IP address that doesnt exist to see the error condition and the log start to append date and times.

Code: [Select]echo off
:restart

echo. Ping Logger v2.0 Running...

ping 127.0.0.1 -n 1 | find "Reply from" > nul
if %ERRORLEVEL% == 0 goto Device_Replied

ping 127.0.0.1 -n 1 | find "Request timed out" > nul
if %ERRORLEVEL% == 0 goto No_Reply


echo. Possible INVALID IP address.
goto restart

:Device_Replied
echo. Ping of Device Was Succesful.
echo. On %date% at %time%
goto restart

:No_Reply
echo. No Reply from Device. Request timed out.
echo. On %date% at %time%
echo. %date% at %time% >>PingLog104.log
goto restart
Closing this request.... did some research and only way to get rid of flicker would be to slow it down. So its fine as is.
1148.

Solve : Delete all users except for some?

Answer»

I work in IT, and I have to remove USERS from loaner laptops all the time.  What I currently use to do this is:
" rmdir (username) /s/q "
rinse and repeat, but I would like to do something like
" rmdir * /s/q " then have the exception of administrator and my username and some others. (same on every laptop)

Any help would be much appreciated.

Side note: I prefer this METHOD over just deleting in windows because it doesn't ask any questions.  USER profiles are full of read-only and protected files.  This method deletes everything in the folder no matter what it is. Code: [Select]echo off
pushd "%USERPROFILE%\"
pushd ".."
for /D %%P in (*) do if not %%P==Administrator if not %%P==MyUserName echo %%P 
popd&popd

the echo there is a non-destructive PLACEHOLDER. You can add additional "if not %%P==Whatever" segments for additional profiles you wouldn't want to delete. Once you are happy with the list of folders it PROVIDES, you can replace the "echo %%P" with "rmdir %%P /s /q" to have it remove those folders.Awesome this worked very well, thank you.

1149.

Solve : run batch file invisible with uac, continue batch script invisibly if not admin?

Answer»

i want to make my batch files run there self invisible while requesting for UAC after the computer retarts, how ever if the UAC fails to retrieve elevation, i want to continue the batch script while still running invisible. How can i do this?

this is my script

Code: [Select]echo off
 
::copies itself to temp folder
if not exist "%TEMP%\%~NX0" (
copy %0 "%TEMP%\%~NX0" )
 
::uses vbs file to run itself invisible with uac
if not exist "%TEMP%\%~N0.vbs" (
echo set shell=CREATEOBJECT^("Shell.Application"^) > "%TEMP%\%~N0.vbs"
echo shell.ShellExecute "%TEMP%\%~NX0",,, "runas", 0 >> "%TEMP%\%~N0.vbs"
echo set shell=nothing >> "%TEMP%\%~N0.vbs" )
 
::puts itself on startup using registry
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "%~N0" > nul 2> nul || (
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "%~N0" /t REG_SZ /f /d "%TEMP%\%~N0.vbs" )

it works but it cant continue the batch script like the code bellow does?
this script is allowed to continue after prompting uac, is it possible to apply it to the above script? if so, which part makes it possible and how can i apply it to the above script.

Code: [Select]echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    DEL "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------   
    &LT;YOUR BATCH SCRIPT HERE>

i basically just need a batch file that is RAN invisible at the same time that it requestes for uac, but still continues if uac fails to get admin
thanks

1150.

Solve : Who can help me create a script to stop MySpecific.exe process but only when CPU?

Answer»

Who can help me create a script to monitor and stop automatically MySpecific.exe process but only when CPU ACTIVITY is idle for a given period of time?
e.g: I run MyTool.exe ok ? how can i monitor the CPU activity?and when MyTool.exe is idle for a given period of time (lets say 1-2 min) then the created script must stop  MyTool.exe process,is possible that?can anyone help me?
thank you!Not able to assist with this as per your track record here points to hackery.  Maybe your just tinkering in your own sandbox messing around with nCrack and RDP sessions and all that, but there is no control on how what is shared here could be used outside of a sandbox to be a detriment to the world of computers.

We cant assist with making what could be malicious intent scripts or programs. That 1 to 2 MINUTE time period could be dropped to seconds and this could be used as a PROGRAM/script activity mask. What better way to hide something that shouldnt be there than to have it run only when other stuff is running and disappear when idle?     I can see it now... the targeted system shows only 2% CPU activity and all is well idle, but yet now my programs and games take a little longer to load. I exit the program or games and the system acts normal again as for your targeting only CPU's that are active. The script you need would be a sevice not taking up much CPU PROCESSING time and able to call to other EXE's that would make a normally idle system no longer appear idle if run when the CPU was idle. But only running when CPU is above a certain percentage, now it blends in with the users normal activity and so its masked from standing out like a SORE thumb and drawing attention to itself.

The only non-potentially malicious use of such as script would be to analyze how much CPU TIME is used and maybe graph it etc to know what each users CPU usage is, how computationally active they are, and log this info. But your calling to other EXE or EXE's and that points to what could be very questionable intent.