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.

1251.

Solve : Deleting Files more than 3 months old?

Answer»

I am trying to fathom out a way of being able to remove files more than 3 months old from a DIRECTORY as part of a housekeeping batch script.

Any ideas would be appreciated...

Ta I am also trying to FIGURE out a way to do this - anybody?There is probably a "work around" method but much depends on whether the files are all "disposable" or whether the directory also CONTAINS "keepers" such as com, exe, dll, and INI files.I have since FOUND out how to do this. Use the utility forfiles.exe, this can be found in the NT Resource kit.

1252.

Solve : Create dynamic directories using date?

Answer»

I need to write a script that creates DIRECTORIES based on the current date. When I use the system VARIABLE DATE the slashes are interpreted incorrectly, therefore the new DIRECTORY becomes 3, eg.

DATE=tue 7/27/2004
set dirvar=%DATE%
md %dirvar%

the directories created are tue 7, 07 and 2004

Any ideas??The forward slash character is not a LEGAL character in a directory name, and is interpretted as a 'new command' initial.

Use country.sys to choose a date format that uses HYPHENS or periods to separate the date values, so you get 200407.27, 27-07-04, or something similar as the name of your directory.

1253.

Solve : Powershell find in compare folder A and B and copy?

Answer»

I have folder A with files which are compressed and copied to folder B
files in folder A have extension .bak, files in folder B have extension .zip, but both have the same name. (Like first is monday.bak and second is monday.zip)
now I need to copy files from folder A to folder C, but only files which doesn't exist in folder B.
For example folder A have files
monday.bak
tuesday.bak
wednesday.bak

Folder B have files
monday.zip
tuesday.zip

Now I need to copy from folder A to folder C what is missing in folder B
and that is file wednesday.bak


I tried this but not WORKING, what I am doing wrong?

CODE: [Select]$path1 = D:\A
$path2 = D:\B
$path3 = D:\C
$fileList = get-childitem $path1 | ?{$_.name -notin $(get-childitem $path2).name }
$filelist.name | copy-item  $path3Do you get any error messages?
You must provide a value expression on the right-hand side of the '-' operator.
Code: [Select]At D:\copy_files.ps1:4 char:47
+ $fileList = get-childitem $path1 | ?{$_.name - <<<< notin $(get-childitem $path2).name }
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpressionHave you Googled what that might mean? Quote from: Salmon Trout on May 15, 2019, 12:15:30 AM

Have you Googled what that might mean?

I did, but I get MANY different RESULTS so don't know what it is
1254.

Solve : logging shell output?

Answer»

Hi,

I need to TAKE the output of a batch file and put it to a log file.  This needs to at the same time output to the screen.  I have tried using tee but SINCE i am using win98se, the batch wont send the output to the screen untill the command(xcopy) in the batch file is done.  But since the command WAITS for the user to anser y or n, the user needs to see the output of xcopy one line at a time, not just all at once when the command is finished.  I will attach my batch file below.  But what I want is to send the output of the batch file to both the screen and a log file.

john

xcopy Z:\JJJ\test\*.* C:\Temp\JJJ\sync\test /v /f /d /s /e /k /-y | tee.exe -a sync%MM%-%dd%-%YY%.logany ideas???

1255.

Solve : Copying a file from a folder with today's date to another folder.?

Answer»

Hello everyone,

I'm hoping someone can help as I'm not the best a creating batch files.

I would like to copy a csv file from a folder and save it in another folder. The source folder is named with today's date (i.e. 06102019) and the destination folder does not change. The CSV will have to overwrite the previous file.

For example:
The batch file will run and look for the folder with today's date
Copy hg200T.csv from C:\monitoring\06102019
Paste (and overwrite existing file) to C:\warning\excel\stream

Thanks in advanceLooking at what you have, the folder which is by name dated NEEDS to be removed daily to remove today yesterdays folder and data?

I have an easy solution for this but I want to confirm some information before sharing the batch script with you as for I don't want to destroy data on you that may be at the destination that goes through a daily purge in prep for new data.

*** Is there any data that needs to remain at C:\warning\excel\stream or can this folder named Stream and all data in the root of Stream and its subfolders be wiped clean of all data and repopulated with the latest data?

Basically the batch I have in mind uses a RD Foldername /S/Q which will remove Stream and all data files and folders and subfolders and then create a new folder named Stream, and then copy the latest CSV file to C:\warning\excel\stream

But holding off on sharing it in this RESPONSE because it can be bad if you plan on any other data remaining at Stream.  QUOTE from: DaveLembke on June 10, 2019, 02:38:28 PM


*** Is there any data that needs to remain at C:\warning\excel\stream or can this folder named Stream and all data in the root of Stream and its subfolders be wiped clean of all data and repopulated with the latest data?



Thanks for the reply. To answer your question, no I will not be needing any info the the stream folder. The stream folder was created to save the daily csv file. I have an excel lookup which checks the daily csv for anomalies. If nothing is found, nothing happens and we move on to the next day. If an ANOMALY is found, an email is sent and we investigate. That's it.

Thanks againUnable to test this at my workplace but this should do the trick. I typed this all up off top of my head without testing. Also to NOTE, I have the batch stepping its way to the destination Stream that is to be destroyed and recreated vs a direct target path. A direct target path could be used but this should do the trick.

XCOPY was used because your dated folder at c:\monitoring with a positive match to hg200T.csv will create the date-named-folder and copy the file over to this C:\warning\excel\stream location.

Code: [Select]c:
cd\.
cd warning
cd excel
rd stream /s/q
md stream
xcopy c:\monitoring\hg200T.csv c:\warning\excel\stream /s/yJust got home from work and tested this on my home computer and forgot to add wildcard * which corrects for the ever changing folder name that is date named.

Here is it corrected and cleaned up:
Code: [Select]rd c:\warning\excel\stream\ /s/q
md c:\warning\excel\stream
xcopy c:\monitoring\*hg200T.csv c:\warning\excel\stream /s/y
1256.

Solve : why does this code output such result?

Answer»

code:

Code: [SELECT]set hi=hi001
set "^=escapeOnly"
set str1="a^!bcd^!efg^^^^^^^^^^^^^!^^^^^^^^^^^!^^^^^^^^^^!hi^^^^^^^^^!^^^^!^!"


echo ----- original ----
echo  !str1!


echo ----- other 4 ----- 2x
echo " %str1%

output:

Code: [Select]----- original ----
 "a!bcd!efg^^^^^^!^^^^^!^^^^^^^escapeOnly "

----- other 4 ----- 2x
" "aefg^!^^escapeOnly "

my confusion is in other 4, I tried to do EXPAND and escape operations to build output in my mind, but I can not understand why my code output this.

thanksWhat is your expected output?look at this link: https://www.dostips.com/forum/viewtopic.php?f=3&t=9137

I want to research how the example in link above works when I assign const STRING to variable str1

thanks

1257.

Solve : Exclude folders from XCOPY instead of just file names??

Answer»

I have used EXCLUDE before to avoid XCOPY'ing certain FILES. But am trying to figure out if there is a way to EXCLUDE folders by Folder Name or not.

OS I am working with is Windows XP Pro BTW

Quote

/EXCLUDE:file1[+file2][+file3]...
               Specifies a list of files containing strings.  Each string
               should be in a SEPARATE line in the files.  When any of the
               strings match any part of the absolute path of the file to be
               copied, that file will be excluded from being copied.  For
               example, specifying a string like \obj\ or .obj will exclude
               all files underneath the directory obj or all files with the
               .obj extension respectively.

Basically I want to xcopy the contents from My Documents and exclude the following folder names

Quote
DYMO LABEL
My Music
My Pictures
My Videos

I know that I can just write a batch pointing out exactly what to grab, but as folders are added this will mean that I'd have to edit my batch accordingly to grab those as well. So I figured I'd check to see if there was an Exclude Trick to target Folder Names to exclude from xcopy's scope?

I suppose I could also perform a wildcard exclusion such as *.jpg *.mp3 etc to avoid certain file types from being targeted that are in those locations. And if there is no way to exclude by folder names I MIGHT just have to create a wildcard listing of file types to exclude. Trying to remember how I did that a while back... I think it was like Quote
xcopy *.* e:\*.* /s/d/y/exclude:<Exclusion_List.txt
to read in exclusion list text file and process, and exclusion list was like this format of 1 line per exclusion
Quote
*.jpg
*.bmp
*.MP3
*.MP4
*.wav
So why aren't you using this for your exclude?
\DYMO LABEL\
\My Music\
\My Pictures\
\My Videos\Adding

Quote
\DYMO LABEL\
\My Music\
\My Pictures\
\My Videos\

in Exclusion_List.txt with instruction of

Quote
xcopy *.* e:\*.* /s/d/y/exclude:<Exclusion_List.txt

Still copies the folders and contents to E: when run from My Documents where the listed folders are within scope deeper ( My Documents\My Music\... etc )   
Quote from: DaveLembke on July 30, 2012, 07:52:30 AM
xcopy *.* e:\*.* /s/d/y/exclude:<Exclusion_List.txt

Try that without the redirection character. Quote from: foxidrive on July 30, 2012, 08:03:47 AM
Try that without the redirection character.
Yeah, what possessed you to use the < with that command. Gonna give that a try...  redirector got stuck in there because I have been playing in MYSQL prompts with batches for too long... sort of same issue I had way back when between DOS and Linux command prompts and / and \  ..LOL

Still an issue... its still grabbing folders that are unwanted with

Quote
xcopy *.* e:\*.* /s/d/y/EXCLUDE:Exclusion_List.txt

hmm...

Exclusion_List.txt file has just this in it and verified spelling and case even though case shouldnt matter if file name matches "Exclusion_List.txt" in DOS shell, so its not missing it due to any naming typos.

Quote
\DYMO LABEL\
\My Music\
\My Pictures\
\My Videos\

Both the batch file and the exclusion text file are in same location, so it should read in contents to exclude from

UPDATE: Also tried

Quote
"\DYMO LABEL\"
"\My Music\"
"\My Pictures\"
"\My Videos\"

to see if the spaces in folder names were causing the issue...   Also tried this pull path in text file to point directly with wildcards to relate all files to exclusion at unwanted folders, even though should be unecessary to have to point exclusively full paths to exclude, as well as account for spaces in folder names by encapsulating it with " " and still having folders and files which should be ignored xcopied across.

Quote
"C:\Documents and Settings\Dave\My Documents\DYMO LABEL\*.*"
"C:\Documents and Settings\Dave\My Documents\My Music\*.*"
"C:\Documents and Settings\Dave\My Documents\My Pictures\*.*"
"C:\Documents and Settings\Dave\My Documents\My Videos\*.*"

 It works fine.

Put this batch file in a folder with a few files and a couple of folders and run it.  In my test it ignores every folder and file under .\abc\


Code: [Select]echo off
md "abc\DYMO LABEL\"
md "abc\My Music\"
md "abc\My Pictures\"
md "abc\My Videos\"

echo abc>"abc\DYMO LABEL\abc.txt"
echo abc>"abc\My Music\abc.txt"
echo abc>"abc\My Pictures\abc.txt"
echo abc>"abc\My Videos\abc.txt"

(
echo \DYMO LABEL\
echo \My Music\
echo \My Pictures\
echo \My Videos\
)>Exclusion_List.txt


xcopy *.* c:\def\*.* /s /d /y /EXCLUDE:Exclusion_List.txt
pause
It is not matching the leading back slash because you were running the command from the ROOT of the My Documents folder.
Thanks for all your help everyone. Getting my 2 typos worked out fixed it!   

Quote
DYMO LABEL\
My Music\
My Pictures\
My Videos\

I personally would do it this way otherwise you are copying over the exclude file and the batch file if you are using a batch file.
Code: [Select]xcopy "My Documents\*.*" H:\backup /s /d /y /EXCLUDE:Exclude.txtThen you can use the leading back slash for the Exclude file.I'm doing something similar, but want my .bat file to live in a different directory. This script seems to work in a test case. Are there any problems with it?
Code: [Select]echo C:\Users\JT\Documents\Scan\abc\>Exclusion_List.txt
xcopy C:\Users\username\Documents\Scan\*.* B:\def\*.* /s /d /y /EXCLUDE:Exclusion_List.txt
pause
Thanks
1258.

Solve : Modify MS-DOS application. exe (without source code)?

Answer»

To all masters,
Pleas Help me and urgent.
The modifications I want are as follows:

1. The display theme, color and company name can be adjusted according to those that can be used by other branches and can be full screen
2. Can print, preview with a USB printer, dot matrix printer and each module can be printed with a choice of print all and print text only and there is also a choice of pages

This application has long been used from 2002 until now & the application was made by the Clipper software.
Note: The application has no source code & if the application can be modified, the source code will be mine.
The source code belongs to me.

Thank you
Note : Extract files that I attach to DRIVE c (C:\Util & C:\STACK).
The application is in the util folder named CAMUS.EXE
I Give the link : https://drive.google.com/drive/folders/1bGX_zULby1A5ZJNo8Y5nqfbR8mzkmYS-?usp=sharing
KanaThis is your source code and you want to modify it ? ?Nobody is going to decompile a clipper application for you for free. There are companies that still make a good MARGIN simply offering that service. Why would anybody do it for you for free?

But that isn't even all you want- You want somebody to decompile a clipper application- then add two non-trivial, involved features to it- for nothing.

Your INSISTENCE on ownership and copyright over the work is somewhat ironic given that you've happily included the registered non-shareware version of PKZIP and PKUNZIP in UTIL.ZIP without a second thought.

Quote from: BC_Programmer on AUGUST 10, 2019, 03:37:02 PM

Nobody is going to decompile a clipper application for you for free.

There's always Stack Exchange...
Quote from: patio on August 10, 2019, 02:36:19 PM
This is your source code and you want to modify it ? ?

this is not my source code and I ask for help for modification Quote from: BC_Programmer on August 10, 2019, 03:37:02 PM
Nobody is going to decompile a clipper application for you for free. There are companies that still make a good margin simply offering that service. Why would anybody do it for you for free?

But that isn't even all you want- You want somebody to decompile a clipper application- then add two non-trivial, involved features to it- for nothing.

Your insistence on ownership and copyright over the work is somewhat ironic given that you've happily included the registered non-shareware version of PKZIP and PKUNZIP in UTIL.ZIP without a second thought.

  Learn to pronounce
fine i will pay
1259.

Solve : Extracting old files created with MSBACKUP?

Answer»

I have a series of 3 very old archived files (created in 1994) which I believe were made with the MSBACKUP utility.  At least, I ASSUME so, as the file headers read "NORTON VER 1E", and that's what research tells me.

I have tried everything I can think of on my Windows 10 machine - direct extraction, DOSBox, downloading and running variants of MSBACKUP - to extract the files, to no avail.  Would anyone have a method that would work, or be willing to do the extract for me?

The file names are CC40919B.001, .002, and .003.  They are each 1.44MB in size.

Thanks in advance.You will need a full VERSION of DOS 6.0 or 6.22.....

See here.

https://www.tek-tips.com/viewthread.cfm?qid=1586851

Instead of goin thru the hassle of installing i'd ask anyone you KNOW if they are running it...or check a PC USER group in your area or a library/school...

Best of Luck.

1260.

Solve : batch file run from task scheduler runs in background. Google was no help?

Answer»

I have a game server that that's launched from a .bat file.

I used task scheduler to set the computer to restart every morning at 0500, and then LAUNCH the .bat at startup.

This is where my problem begins.

when I manually launch the server via double clicking the .bat, it opens CMD and runs as intended.

When the task scheduler event runs and launches the server, it works... but it's running in the background and I have no way to see what it's doing. If something goes wrong, I can't tell without opening perfmon and looking at my system's resource consumption.

Thats problem 1.

Problem 2 is if my server crashes or closes, it stays off until I either notice, or 0500 rolls around.

I THOUGHT to ADD "goto START" at the end... but that just causes the server to launch over and over until the entire system bogs down and becomes unresponsive

ANY assistance would be greatly appreciated!

Heres a copy of my .bat:

:Backup
echo off
echo Waiting for backup to Start! /t 10 sec
timeout /t 10
echo Thanks for waiting
title Atlas Server Batch Backup Started!
For /f "tokens=1-3 delims=//" %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
xcopy /s "D:\AtlasSrv\ShooterGame\Saved" "D:\ServBackups\Atlas\%mydate%_%mytime%\"
echo Backup created!
echo off
echo backup Completed! /t 10 sec
timeout /t 10
echo  Thanks for waiting!
goto :UPDATE
:UPDATE
echo Starting game update!
echo %time%: Starting game update>>restartlog.txt
cd %steamcmd_path%
start D:\AtlasSrv\SteamCMD\steamcmd.exe +login anonymous +force_install_dir D:\AtlasSrv\ +app_update 1006030 validate +quit
goto :WAITFORUPDATE
:WAITFORUPDATE
echo off
echo Waiting for update to finish! /t 1000 sec
timeout /t 1000
echo Thanks for waiting.. Starting Server in 10 sec!
timeout /t 10
goto :START
:START
start D:\AtlasSrv\ShooterGame\Binaries\Win64\ShooterGameServer.exe BLACKWOOD?ServerX=0?ServerY=0?AltSaveDirectoryName=10?ServerAdminPassword=*********?MaxPlayers=50?ReservedPlayerSlots=25?QueryPort=57582?Port=5761? -log -server -NoBattlEye -NoSeamlessServer
Two things to try

1. When you schedule the task, if you set it to run as the user that will be logged in at the time, it should run in the foreground. There is also a "Hidden" checkbox under the general tab. Ensure that is unchecked.

2. In the Scheduled Task properties, under the 'Actions' tab, choose your action and click edit. Under the program/script field, change this to

cmd

Under the add arguments field, change this to

/k "C:\path\to\job.bat"

Modifying it to your actual batch drive, path, and name of course!

1261.

Solve : i didnt know where to put this so...?

Answer»

BASICALLY..  

i deleted the partition windows was on and i dont have n e other partitions and i was wondering if i could fix that?SORRY, I think you are domed.
IvanI ASSUME you mean you formatted your ENTIRE disk?

Unless you are willing to spend a lot of money to buy programs that MAY be ABLE to recover a slight portion of your hard drive; donot bother.You could just use the recover command in the DOS window.Try this:  http://www.partition-recovery.com/

1262.

Solve : Get error: program to big to fit in memory?

Answer»

Does anyone know how i can fix this problem and start the program.
ThankuAre RUNNING under DOS? A command prompt in Windows? How much memory do you have?yeah i have 256 meg of ram and i am running the prompt in windows xp
You need to add more memory. Contrary to what M$ says (they are proven liars ) thats not enough for XP to ramble in and do much of anything else. If you have a lot programs loading at startup, disable anything that you don't use on a very regular basis. Also disable any services that are not necessary. A GOOD place for guidance on services is http://www.blackviper.com/WinXP/servicecfg.htm Quote

yeah i have 256 meg of ram and i am running the prompt in windows xp


At the prompt, type "mem" (without the ").  640K is largest executible program SIZE.  Adding memory will do nothing to help.
CC, you are still in the days DOS 3. Do you really THINK anything runs now in 640K?WEll is there another way i can allocate more memory or is there another disk operating SYSTEM that i can use to open this fileIf this is a DOS app, you will need to use the compatibility wizard or make a couple of small FAT32 partitions exclusively for DOS 7 (DOS from Win9x) to run the app in a separate bootup environment. A partition manager and a second hard drive are very much recommended here if you decide to use the separate OS.

Or you could use Linux and an appropriate command-line shell...how do i partition a file for fat32 if i am running a ntfs file systemIf you have a PowerQuest PartitionMagic, you can knock back a couple of gig on your hard drive and mount a DOS 7 primary partition, then access it with the boot manager. You mount your game so it runs from the DOS partition.

If you get an old 8 to 20 GB HD, you can mount it and partition it as your second HD and either make it all FAT32 for DOS7.1 and (optionally) Win98, or you can make it a few GB for DOS and the re3st NTFS for your main OS...
1263.

Solve : How to fix command output into variable?

Answer»

Hi!

I tried to send command output to variable.
I'm using is in Windows 10.1903 x64
I used syntax:

Code: [Select]SET /P variable= | command
I used batch by context menu to get word, characters and lines count in text file using old WC tool (it's great).
First I used only COPYING output into clipboard by:

Code: [Select]wc %1 | clip
which output format is:

Code: [Select]extension description.txt:  WORDS: 173        Lines: 31         Chars: 1195
I WANT also to show message with the same content by MSG command in syntax:

Code: [Select]msg title "text"
So, finally batch code is this:

Code: [Select]wc %1 | clip
SET /P count= | wc %1
msg Word count "%count%"
exit
But new problem - file is not found - even copy to clipboard works not and here's output:

Code: [Select]WARNING!  File: " E:\Documents\__Registry\Word Count\message.bat" not found.

      Word Count (freeware)
  TawbaWare software, August 1999
http://members.tripod.com/~tawba

Usage: WC [-w] [-c] [-l] [-a] [filename]

Options:
-w Print word count
-c Print character count
-l Print line count
-a Print grammatical analysis

If no options are entered, program displays all items,
EXCLUDING grammatical analysis.
It looks easy to see that problem is in path (I included quotes to see it).
So, Q is - how to remove first space from file path? Yes, it is possible to read %1 into variable from 2nd char, but first I checked if is %1 argument copied into variable
So, I tried this:

Code: [Select]SET /P file= | %1
wc %file% | clip
SET /P count= | wc %file%
msg Word count "%count%"
exit
But no output, nothing. So, before cutting path I need to put file path into variable

Really if anyone know where do I mistake, please correct me.
Thank you all.
Miro

1264.

Solve : Wait Process Window to be Activate?

Answer»

I'm using a powershell script:

  Start-process c:\test\WINDOW.exe

I'm trying to make it WAIT "window.exe" be activate to continue the script.What do you mean "be activate"?
Quote from: Salmon Trout on September 15, 2019, 01:59:11 AM

What do you mean "be activate"?

Hi, i mean wait to the window process show in the screen.Clear as MUD... Quote from: PATIO on September 15, 2019, 08:06:15 AM
Clear as Mud...

Sorry 

Code: [Select]  Start-process c:\test\window.exe It's as login window, that take a while to appear depending on HARDWARE.
1265.

Solve : WIN/BATCH Help with batch program for updating library?

Answer»

Hello

I'm working on program for updating library I made something by others from another forums and got it together but I got problem.

The program should be like this: On desktop will be batch file if I open it, it should detect latest available update based on the name of the folder. The source folder with available updates is in another hard drive (G) There is more versions it LOOKS like this: 

V5_Update_20.22.dir
V5_Update_20.23.dir
V5_Update_20.24.dir
V5_Update_20.25.dir
V5_Update_20.26.dir
V5_Update_20.27.dir

Then It should detect my actual version based on name too, but it is in another hard drive where should be updated the files.

There should be detectable versions like this for program

Catalogumfang_20.22.txt
Catalogumfang_20.23.txt

Based on this it should know which is higher version and it should be copyed like this

content of:
V5_Update_20.24.dir (after DONE go on another version)
V5_Update_20.25.dir (after done go on another version)
V5_Update_20.26.dir (after done go on another version)
V5_Update_20.27.dir (after done go on another version)
-------------------------------------------------------------------------------------
And I'm stuck here: (it only detect version in folder where is batch LOCATED. How can I give it path where is located the source if I put the batch on dekstop)

echo off
setlocal enabledelayedexpansion
set max=0
for %%x in (V5_Update_*) do (
  set "FN=%%~nx"
  set "FN=!FN:V5_Update_=!"
  if !FN! GTR !max! set max=!FN!
)
echo AUDI library latest version: V5_Update_%max%

pause

Thank you guys.The only way I could get a dir list was to change the FOR loop. As I do not have a G: drive I used F: instead. The folders V5_Update_20.22.dir, V5_Update_20.23.dir, etc, are in my folder F:\test. See red bold below. The script works when run from anywhere. The echo commands in the loop are just for testing. You can hard-code the parent folder like below or you can make it a %VAR% or even pass it to the script as a parameter (e.g. %1). Nobody ever ANSWERS my batch solutions, so good luck!

echo off
setlocal enabledelayedexpansion
set max=0
for /f "delims=" %%x in ('dir /ad /b "f:\test\V5_Update_*"') do (
  set "FN=%%~nx"
  echo FN  = !FN!
  set "FN=!FN:V5_Update_=!"
  echo FN  = !FN!
  if !FN! GTR !max! set max=!FN!
  echo max = !max!
)
echo AUDI library latest version: V5_Update_%max%

pause

1266.

Solve : Hostname to nslookup via batch file?

Answer»

Hello,

What i would like to achieve in a batch file:
Hostname resolve to IP address and from the ip address -> nslookup the ip to resolve the hostname from a csv file (Hostname.csv).

in csv file will contain only the hostname -> Hostname.csv
and the result output tab should contain:
Hostname | ip address | NSlookup hostname -> result.csv

Thanks
Hi 
Can you provide us an example of your input csv file ?
How is the file constructed, that is, what is the delimiter ?
So, your PROBLEM how to get the ip adress from the hostname ?Hi,

Below is somewhat im trying

echo off
for /f %%i in (location of file\hostname.csv) do Call :StartPing %%i
goto :eof

:StartPing
PING %1 -N 1| FIND /i "TTL" > nul && goto Success
PING %1 -n 1| FIND /i "timed" > nul && goto Timedout
PING %1 -n 1 -w 400 | FIND /i "TTL" > nul || goto ErrorMsg
goto :EOF

:Success
for /F "tokens=3" %%a in ('ping %1 ^| find /i "TTL"') do set Address=%%a
for /F "tokens=2" %%a in ('ping -a %Address::=% ^| find /i "pinging"') do set HostName=%%a

set IPAddress=%Address::=%
echo %1, %IPAddress%,%Hostname%

for /f "tokens=2" %%a in ('nslookup %IPAddress% ^| find /i "Name: " ') do set "nsNAME=%%a"
echo "%nsname%"

echo %1, %IPAddress%,%Hostname% >> location of file Results.csv
goto :EOF

:Timedout
Echo %1, Request timed out.
Echo %1, Request timed out. >> location of file Results.csv
goto :EOF

:ErrorMsg
Echo %1, Ping request could not find host.
Echo %1, Ping request could not find host. >> Results.csv
goto :EOF

im stuck with nslookup export

delimiter -> Hostname;ip adress;nslookup hostname (output should have this result altogther)

hostname.csv -> are simply a list with hostname e.g computer 1
                                                                             computer 2

Thanks for the big HELP.

1267.

Solve : Batch Advice?

Answer»

I am a desktop administrator and I am using c$ all day in order to backdoor into devices on our domain. I am trying to create a batch file that will speed up this process and honestly would like to just learn a little bit more on this and what I have available to me. I want the script to prompt for the Host Name of the DEVICE that I am trying to backdoor into then ask for the administrator password. I am utterly failing at making this work, any help or advice would be greatly appreciated. How did you get this job ? ?Instead of looking to write a batch file to do what you are typing etc. Why not use a macro recorder and let it do the repetitive things you do each day. Quote from: patio on September 30, 2019, 08:52:08 PM

How did you get this job ? ?

You realize that I can be a desktop admin and not know coding right? I can also just go ahead and report you for being assinine. If you have no intelligent comment maybe just IDK stop typing?I posted on this forum because after reading a couple posts it looked like a helpful and intelligent GROUP of people looking to genuinely help people learn and write scripts/powershell and stuff like that. I honestly think people are just on here now to flame others. Thanks, but no thanks. Legit first post and a moderator comes in and tries to invalidate my work ethic and job. I went out wanting to learn more, that kind of behavior is childish as *censored*.Your use of the term backdoor was probably the trouble, as a backdoor is generally an *unauthorized* way of gaining access to a system- like a secret password left in by a developer so they can muck about if they get fired or whatever. The concern was, I think, that you were accessing remote systems without authorization. Presumably that is not what you mean.

You should be fine to use the net use COMMAND \\Host\C$ /user: ...Not sure what you intend to automate. I suppose, you could have a script prompt for the username/pass/hostname first?

Code: [Select]echo Enter Host Name to connect
set /p useHost=
echo Enter username
set /p useUser=
echo Enter password
set /p usePassword=
net use \\%useHost%\C$ /user:%useUser% %usePassword%
explorer \\%useHost%\C$

If the username is the same across them (Administrator for example) You could remove the prompt and have it only ask for the password. net use probably returns an errorlevel if it fails as well in which case it would be reasonable to not run explorer trying to load up the share folder too, but this is the basic idea.Given the stated task i asked my question because it would have been part of your job DESCRIPTION...
If i offended you i apologise but i think you are in over head...
Best of luck. Quote from: patio on October 01, 2019, 07:10:40 PM
Given the stated task i asked my question because it would have been part of your job description...
If i offended you i apologise but i think you are in over head...
Best of luck.

I am a desktop administrator....I replace keyboards, troubleshoot systems...I am honestly just dabbling in programming and what not to try to learn. I'd just watch how you talk to people because it kinda sucks to be shut down when you are trying to learn something. Quote from: BC_Programmer on October 01, 2019, 10:08:56 AM
Your use of the term backdoor was probably the trouble, as a backdoor is generally an *unauthorized* way of gaining access to a system- like a secret password left in by a developer so they can muck about if they get fired or whatever. The concern was, I think, that you were accessing remote systems without authorization. Presumably that is not what you mean.

You should be fine to use the net use command \\Host\C$ /user:<username> <password> ...Not sure what you intend to automate. I suppose, you could have a script prompt for the username/pass/hostname first?

Code: [Select]echo Enter Host Name to connect
set /p useHost=
echo Enter username
set /p useUser=
echo Enter password
set /p usePassword=
net use \\%useHost%\C$ /user:%useUser% %usePassword%
explorer \\%useHost%\C$

If the username is the same across them (Administrator for example) You could remove the prompt and have it only ask for the password. net use probably returns an errorlevel if it fails as well in which case it would be reasonable to not run explorer trying to load up the share folder too, but this is the basic idea.

I'll give this a shot. Yeah, I use backdoor freely. At work I am constantly sending files to and from devices. It's just easier to prompt for admin password and pc name and let me right into the c drive. Makes life easy. Time to study.So I think I FIGURED it out. It's running in a batch script and asks for just my password. Feels good. I really appreciate the help with this. Saves me a very small amount of time...but it was a lot of fun. Sorry for getting upset it's just that this was my first real attempt and it felt like I was just getting pointed at and laughed at lol. Either way, page bookmarked.
1268.

Solve : Auto Center Vbs Window?

Answer»

Hello to all,

sorry if i post in wrong section.
This is script does what i need, i'm just need to know how to do "window auto center", "get the message in the center of the box" and put a "countdown", in this script.

Thanks for any help.

Code: [Select]with HTABox("DodgerBlue", 100, 300, 0, 0)
  .document.title = "Atualizando Sistema"
  .msg.innerHTML = "<font color=red><b>ATUALIZANDO SISTEMA, AGUARDE.<b></font>"
  Timeout = 60000 ' milliseconds
  do until .done.value or (n > TimeOut): wsh.sleep 50 : n=n+50 : loop
  .done.value = true
  .close
END with

' Author Tom Lavedas, June 2010
Function HTABox(sBgColor, h, w, l, t)
Dim IE, HTA

  randomize : nRnd = Int(1000000 * rnd)
  sCmd = "mshta.exe ""javascript:{new " _
       & "ActiveXObject(""InternetExplorer.Application"")" _
       & ".PutProperty('" & nRnd & "',window);" _
       & "window.resizeTo(" & 500 & "," & 500 & ");" _
       & "window.moveTo(" & l & "," & t & ")}"""

  with CreateObject("WScript.Shell")
    .Run sCmd, 1, False
    do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
  end with ' WSHShell

  For Each IE In CreateObject("Shell.Application").windows
    If IsObject(IE.GetProperty(nRnd)) Then
      set HTABox = IE.GetProperty(nRnd)
      IE.Quit
      HTABox.document.title = "HTABox"
      HTABox.document.write _
               "<HTA:Application contextMenu=no border=thin " _
             & "minimizebutton=no maximizebutton=no sysmenu=no />" _
             & "<body scroll=no style='background-color:" _
             & sBgColor & ";font:normal 14pt Arial Black;" _
             & "border-Style:outset;border-Width:10px'" _
             & "onbeforeunload='vbscript:if not done.value then " _
             & "window.event.cancelBubble=true:" _
             & "window.event.returnValue=false:" _
             & "done.value=true:end if'>" _
             & "<input type=hidden id=done value=false>" _
             & "<center><span id=msg>&nbsp;</span><center></body>"
      Exit Function
    End If
  Next

' I can't imagine how this LINE can be reached, but just in case
  MsgBox "HTA window not found."
  wsh.quit

End FunctionJust give a try for this code with countdown :
Code: [Select]with HTABox("DodgerBlue", 100, 100, 500, 300)
.document.title = "Atualizando Sistema"
nMinutes = 01
nSeconds = 00
do until (nMinutes + nSeconds < 1)
.msg.innerHTML = "<font color=red><b>ATUALIZANDO SISTEMA, AGUARDE.<b><br>" &_
Right("0"&nMinutes,2) & ":" & Right("0"&nSeconds, 2)&"</b></font><br>"
Wait 1
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
Loop
.done.value = true
.close
end with
'********************************************************************************************
Sub Wait(Seconds)
Dim ws
Set ws = CreateObject ("WScript.Shell")
ws.Run "Cmd /c Timeout /T " & Seconds & " /nobreak", 0, True
End Sub
'********************************************************************************************
' Author Tom Lavedas, June 2010
Function HTABox(sBgColor, h, w, l, t)
Dim IE, HTA
randomize : nRnd = Int(1000000 * rnd)
sCmd = "mshta.exe ""javascript:{new " _
& "ActiveXObject(""InternetExplorer.Application"")" _
& ".PutProperty('" & nRnd & "',window);" _
& "window.resizeTo(" & 450 & "," & 130 & ");" _
& "window.moveTo(" & l & "," & t & ")}"""

with CreateObject("WScript.Shell")
.Run sCmd, 1, False
do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
end with ' WSHShell

For Each IE In CreateObject("Shell.Application").windows
If IsObject(IE.GetProperty(nRnd)) Then
set HTABox = IE.GetProperty(nRnd)
IE.Quit
HTABox.document.title = "HTABox"
HTABox.document.write _
"<HTA:Application contextMenu=no border=thin " _
& "minimizebutton=no maximizebutton=no sysmenu=no />" _
& "<body scroll=no style='background-color:" _
& sBgColor & ";font:normal 14pt Arial Black;" _
& "border-Style:outset;border-Width:10px'" _
& "onbeforeunload='vbscript:if not done.value then " _
& "window.event.cancelBubble=true:" _
& "window.event.returnValue=false:" _
& "done.value=true:end if'>" _
& "<input type=hidden id=done value=false>" _
& "<center><span id=msg>&nbsp;</span><center></body>"
Exit Function
End If
Next
' I can't imagine how this line can be reached, but just in case
MsgBox "HTA window not found."
wsh.quit
End FunctionHere is another code but you should execute it as HTA file not as VBS file :
So, just copy and paste this code as name Countdown.hta
Code: [Select]<HTML>
<HEAD>
<Title>ATUALIZANDO SISTEMA, AGUARDE ...</Title>
<HTA:APPLICATION
ICON = "magnify.exe"
BORDER="THIN"
INNERBORDER="NO"
MAXIMIZEBUTTON="NO"
MINIMIZEBUTTON="NO"
SCROLL="NO"
SYSMENU="NO"
SELECTION="NO"
SINGLEINSTANCE="YES">
</HEAD>
<BODY text="Red"><CENTER>
<b><marquee DIRECTION="LEFT" SCROLLAMOUNT="3" BEHAVIOR=ALTERNATE><font color="red" face="Tahoma">ATUALIZANDO SISTEMA, AGUARDE ... </font></marquee></b>
<b><span id="countdown"></span></b>
<img src="data:image/gif;base64,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" />
</CENTER></BODY>
</HTML>
<SCRIPT LANGUAGE="VBScript">
Set ws = CreateObject("wscript.Shell")
Sub window_onload()
    CenterWindow 400,120
    Self.document.bgColor = "DodgerBlue"
Call CountDownToClose(01,00) '1 minute countdown
 End Sub
'--------------------------------------------------------------------
 Sub CenterWindow(x,y)
    Dim iLeft,itop
    window.resizeTo x,y
    iLeft = window.screen.availWidth/2 - x/2
    itop = window.screen.availHeight/2 - y/2
    window.moveTo ileft,itop
End Sub
'--------------------------------------------------------------------
Sub CountDownToClose(nMinutes,nSeconds)
do until (nMinutes + nSeconds < 1)
countdown.innerHTML = Right("0"&nMinutes,2) & ":" & Right("0"&nSeconds, 2)&"<br>"
Wait 1
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
Loop
Self.close
End Sub
'--------------------------------------------------------------------
Sub Wait(Seconds)
Dim ws
Set ws = CreateObject ("WScript.Shell")
ws.Run "Cmd /c Timeout /T " & Seconds & " /nobreak", 0, True
End Sub
'--------------------------------------------------------------------
</script>

1269.

Solve : batch close after powershell script?

Answer»

Hello all, I need some help with this :

Code: [Select]echo off
path %path%; C:\windows\temp
echo ouverture du RDP
POWERSHELL -command "Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -value 0"
echo installation de boxstarter
powershell -command "Set-ExecutionPolicy Unrestricted -Force"
powershell -command ". { iwr -useb https://boxstarter.org/bootstrapper.ps1 } | iex; get-boxstarter -Force"
echo copie du script PowerShell vers le dossier temporaire de Windows
copy "\\ftp-stg1\FTP Root\Programs\script\vmprog.ps1" C:\Windows\Temp
echo copie du script CMD vers le dossier temporaire de Windows
copy "\\ftp-stg1\FTP Root\Programs\script\package_install.cmd" C:\Windows\Temp
echo appel du script d installation
call package_install.cmd
exit
the scrip closes after this command Code: [Select]powershell -command ". { iwr -useb https://boxstarter.org/bootstrapper.ps1 } | iex; get-boxstarter -Force"the powershell PROCESS need to be closed, in order to run this other part of the script Code: [Select]echo debut de l'installation des programmes avec choco
powershell -command "Install-BoxstarterPackage -PackageName "C:\Windows\Temp\vmprog.ps1"" whitch is in package_install.cmd.

If POSSIBLE, I'd like to run all the COMMANDS in one single batch...
Let me know if I'm making sens...

1270.

Solve : How to escape special characters on InputFile with Drag and Drop ??

Answer»

Hi   
The goal of this code is to drag and drop a file onto the script and it encodes or decodes it in Base64 with Certutil Command.
So my question is : "What can i do to escape special characters when a file to be encoded or DECODED have them ?"
Thank you !
Code: [Select]echo off
Set "file=%~1"
If "%file%"=="" GOTO:EOF
&GT;nul find "-----BEGIN CERTIFICATE-----" "%file%" && (
 certutil -f -v -decode "%file%" "%file%"
) || (
 certutil -f -v -encode "%file%" "%file%"
)
EXITIn C++ I have had to escape the escape character such as \\. In BATCH you should also be able to do the same by a double escape using a batch escape character. The first escape is saying to escape the literal escape character. https://www.robvanderwoude.com/escapechars.phpI got a solution, so the problem is solved 
Code: [Select]echo off
Title Encode and Decode files into B64
setlocal enableextensions enabledelayedexpansion
set "COUNT=0"
set scr="%~f0"
set "cmd=!cmdcmdline:*%~f0=!"
set "ARGS=!cmd:~0,-1!"
set "args=!args:* =!"

for %%f in (!args!) do (
   set /a "count+=1"
   set infull[!count!]="%%~f"
)

for /l %%i in (1,1,!count!) do (
   Set "file=!infull[%%i]!"
)

If [!file!]==[] GOTO:EOF
echo !file! & pause

>nul 2>&1 find /I "-----BEGIN CERTIFICATE-----" !file! && (
certutil -f -v -decode !file! !file!
) || (
certutil -f -v -encode !file! !file!
)
pause
Exit

1271.

Solve : Batch file: Deleting duplicate files within similar folder structures?

Answer»

Create a batch file to only delete DUPLICATE files (same filename, date/time) in the same relative FOLDER location.  New folder\files along with the .bat file are placed here: \TEST\NEW\.  Old files are in \TEST\OLD\.
Folder \OLD\ contains many folders that have the same structure as the folder under \NEW\.  The intent is to delete all of the duplicate files under \OLD\ which are the same filename, date\time, and relative location in the folder structure.
\TEST\OLD\1\15\1a.txt or \TEST\OLD\3\15\1a.txt would be deleted if \TEST\NEW\1\15\1a.txt existed and has the same date\time. 

I started with which does not seem to work -

CODE: [Select]for %%F in ("d:\test2\new\**") do (
    if exist "d:\test2\old\%%~nxF" del "d:\test2\old\%%~nxF"
)Your SCRIPT only deletes files in D:\OLD\ (just that folder) if the same name file exists in D:\NEW\ (just that folder). However, you seem to want to go deeper in the folders, and there is nothing about file date in your script.This is what I've been able to research/apply.  As before, the following deletes all occurrences of 1a.txt within the \Old\ path structure regardless of file modified date or size and path.  Even if a file of the same name/date/size exist within the \Old\ structure, only those which also match the path from the fourth level and below are to be deleted.

Code: [Select]SETLOCAL enableextensions
pushd "D:\test2\old\"
for /F "delims=" %%G in ('dir /B /S /A:-D *.*') do (
  call :FileComp "%%~fG" "D:\test2\new\%%~nxG"
)
popd
ENDLOCAL
goto :eof

:UpError
exit /B %1

:FileComp
  call :UpError 321
  fc /B "%~1" "%~2" >NUL 2>&1
  if not %errorlevel% EQU 0 (
    del "%~1"
  ) else (
    echo %errorlevel% "%~2"
  )
goto :eofHi 
I don't know if this can be helpful to you in your situation ==> Compare files from two folders using HASH SHA1 in BATCHI'd use long filenames so that every copy would have a unique name
Put them all in one folder
and look at them in SIZE order..
manually deleting those that are duplicates.

1272.

Solve : DVD will not work in DOS?

Answer»

How do I get MS-DOS to see DVD player? I have two drives. One with Windows 10, and the other drive with MS-DOS. My DOS drive is labeled drive E. At C PROMPTED, I cannot change to E prompt. It WOULD say "Invalid drive".  Simple answer is that you don't.
Instead of using an old version of MS-DOS, use a recent Windows system to see the DVD drive.
A workaround is to use ANOTHER version of DOS that has the right drivers already installed. However, as I recall, they only work on a CD drive, not a DVD.

You may want to read this article:
https://en.wikipedia.org/wiki/MSCDEX
Quote

MSCDEX or Microsoft CD-ROM Extensions is a software program produced by Microsoft and included with MS-DOS 6.x[1] and certain versions of Windows to provide CD-ROM support.[2] Earlier versions of MSCDEX since 1986 were installable add-ons for MS-DOS 3.1 and HIGHER.[
May I snuggest a quick workaround ?
Copy DVD files to USB stick and take it to the MS-DOS PC.Generic CD-ROM drivers such as OAKCDROM.SYS work for DVD drives and you can in fact read most DVDs from within DOS.Thanks for the help. That's good information for me. Hi Alan,

You don't say what machine the dvd is in and what connection on the motherboard you are using if it is sata you will need gcdrom.sys from here http://help.fdos.org/en/hhstndrd/base/gcdrom.htm

Your harddrive will need a config.sys file and autoexec.bat file and have the lines ADDED shown on that page.Hi. This is a home-built machine. The DVD is an ASUS SATA. The motherboard is an ASUS Prime X370-PRO. Then you will need  gcdrom.sys
As per the website
1273.

Solve : if and else routine returns an error?

Answer»

echo off
setlocal EnableDelayedExpansion
for /f %%i in (filename.txt) do (dsquery user -samid %%i | dsget user -memberof | findstr /c:"string" > nul
if !errorlevel! == 0 (
   echo %%i is a member
 ) ELSE (
   echo %%i is NOT a member
 )
)
endlocal

this batch file returns "%i is NOT a member"

I checked my syntax, tried different OPTIONS for 'errorlevel' but no luck, before the message the batch takes about 5 minutes. what am I doing wrong?In batch string compares, white space counts, so this if !errorlevel! == 0 is comparing !errorlevel! and a space, with a space plus "0", and this will never be true.

Either do this if !errorlevel!==0 or else do a number compare: if !errorlevel! equ 0
thank you for answering my post, I truly appreciate it. I've been rolling on the ground with this thing for a while now.

I did try your suggestion I amended the line to read "if !errorlevel!==0" and then to "if !errorlevel! equ 0"; still I got the same erroneous outcome "%i is NOT a member" which suggest I'm doing something wrong.

please advise.
Why don't you try echoing some of the variables and looking at them? ALSO not redirecting the command to nul? Is the file really called filename.txt? Do the LINES in filename.txt contain spaces?
I will make the batch file display as it processes; and report back or if I figure it out I will report what I did.
the name of the file is mgr.txt, and no, it does not have spaces. Actually this part of the code works:


for /f %%i in (mgr.txt) do (dsquery user -samid %%i | dsget user -memberof | findstr /C:"Syncplicity"

so, that part of the code is solid and proven.

note: when I run this is the command line I remove the second % symbol.

note: when run as above I add the >>file.txt line, but of course all I get is the name of the distinguished name of the group, which is useless.

What I'm trying to do is compare the usernames contained in mgr.txt to the names in the Syncplicity AD group. I would like for the routine to take the name from the text file and see if Syncplicity is one of the groups the users belongs to. if the user belongs to the group I'd like for the routine to display "xyxyxy" is a member, alternatively to display "xyxyxy" is NOT a member.

the original batch file would do this for one user, I ran the batch file like this "syncme xyxyxy". the batch file would run and RETURN with the message desired. I tested the results of the file extensively and the results were trustworthy. So, the original file looks like this:

echo off
dsquery user -samid %1 | dsget user -memberof | findstr /c:"Syncplicity" > nul
if %errorlevel% == 0 (
   echo %1 is a member
) ELSE (
   echo %1 is NOT a member
)

What does this do?

echo off
setlocal enabledelayedexpansion
for /f %%i in (mgr.txt) do (
   echo testing %%i
   dsquery user -samid %%i | dsget user -memberof | findstr /c:"Syncplicity"
   REM > nul
   echo errorlevel is: !errorlevel!
   if !errorlevel==0 (
      echo %%i is a member
   ) ELSE (
      echo %%i is NOT a member
   )
)

Fixed fatal typing error! Sorry!

echo off
setlocal enabledelayedexpansion
for /f %%i in (mgr.txt) do (
   echo testing %%i
   dsquery user -samid %%i | dsget user -memberof | findstr /c:"Syncplicity"
   REM > nul
   echo errorlevel is: !errorlevel!
   if !errorlevel!==0 (
      echo %%i is a member
   ) ELSE (
      echo %%i is NOT a member
   )
)


wild4bits,
You are getting good advice from Salmon Trout.

Now then, for what it is worth, many users are moving away from pure Batch file USE. Instead, they use alternative methods that are easier to kern.

One is Power Shell, now s part of Windows.
Or even VB Script, which is very versatile.
And there are a number of other programs. That  make a claim to fame.
 
I would recommend VB Script .
Quote

VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It allows Microsoft Windows system administrators to generate powerful tools for managing computers with error handling, subroutines, and other advanced programming construct
Wikipedia › wiki › VBScript
Here is a introduction:
https://www.guru99.com/introduction-to-vbscript.html
IMHO, using Vb Script is abetter choice for most users.
1274.

Solve : How to boot to DOS from diskette reading HDD config??

Answer» HI!

I'm using MS-DOS 7.10 and want to boot into by floppy disk.
I tried to modify AUTOEXEC.BAT on floppy to use commands and software from harddisk, but it is always using floppy commands and software.

How is possible to boot DOS from floppy but reading harddisk config?
I know that is possible to fix booting from HDD by SYS C: command, but I need to leave on HDD GRUB and untouched.
Or: is possible to fix GRUB that will correctly enter DOS?
It always reports error on item CREATED for DOS.

Thank you for understanding.
MiroSetting up a fully working DOS system will give you great appreciation for how far computing has come.  For old-timers, it will be a walk down memory lane; for youngsters who've never used nor even SEEN DOS before, it should be quite an eye-opening experience to experience first hand both how primitive DOS was and yet how capable it could be. Quote from: tinamonday on October 04, 2019, 11:42:03 AM
Setting up a fully working DOS system... bla bla bla...

How does that answer the question? Here is video tutorial about how to install DOS 7.1 from you tube.
https://www.youtube.com/watch?v=N2SPlHzAcSI
That should answer his questions.
You can set the PATH variable to point to folders on C:
He has refused to get a legit version of DOS 6.2 to work with...thats why i stopped volunteering information.  Just sayin. Quote from: patio on October 05, 2019, 08:29:33 PM
He has refused to get a legit version of DOS 6.2 to work with...thats why i stopped volunteering information.  Just sayin.
Good point.
For anybody that WANTS to do DOS programming and does not want to pay for it, he ought to consider using a Free version of DOS.

https://en.wikipedia.org/wiki/FreeDOS
Quote
FreeDOS (formerly Free-DOS and PD-DOS) is a free operating system for IBM PC compatible computers. It intends to provide a complete DOS-compatible environment for running legacy software and supporting embedded system
It is compatible with with Windows.
It can be used for almost any job that would require MS-DOS.He just has to add this line to the autoexec.bat on the boot floppy, assuming he has a standard MS-DOS layout on the C: drive, with system executables in C:\DOS:

PATH C:\;C:\DOS

Really, this is so elementary that a child could find it out.

1275.

Solve : Need help with choice and if?

Answer»

hey,
I'm trying to make a sort of GANE launcher with batch. Basically a few choice's and if's but after the first choice the if's seem to do nothing as no matter my input it always opens the first game of the list.
And i've tried using set /p but the same problem occured

(And, yes, I probably made same embarrassing mistakes but am not  programer, first time coding)

Here my code so far:

echo off

mode CON: cols=1024

:START
Echo Press 1 for GBA or 2 for SNES
choice/c 12 /n

if %errorlevel%==1 (Echo Choose game
Echo 1 Castlevania - Aria of Sorrow
Echo 2 Keitan Denjuu Telefang
Echo 3
Echo 4
Echo 5
Echo 6
Echo 7
Echo 8
Echo 9
Echo 0 Return
choice /c 1234567890 /n

if "%errorlevel%"=="1" goto 1
if "%errorlevel%"=="0" goto START

:1
"C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Keitai Denjuu Telefang - Speed Version (Japan).gbc"
)

if %errorlevel%==2 (Echo Choose game
Echo 1 Blackthorne

choice /c 123456789 /n

   if %errorlevel%==2 "C:\Emuladores\zsnesw151\zsnesw.exe" "C:\Emuladores\zsnesw151\ROMs\Blackthorne (USA).sfc"
   exit)I figured it out! Just used a GOTO command with all the IFs stacked together just calling the GOTOs.
Still if anyone has any hints on optimazation it be appreciated.
Posting the code to see if it helps others.

Code:

ECHO OFF

:MENU
Echo Press 1 for GBA or 2 for SNES
CHOICE /C 12 /N


IF %ERRORLEVEL%==1 GOTO GBA
IF %ERRORLEVEL%==2 GOTO SNES
EXIT

:GBA
ECHO ------Choose Game------
ECHO 1 A-C
ECHO 2 D-F
ECHO 3 G-I
ECHO 4 J-L
ECHO 5 M-O
ECHO 6 P-R
ECHO 7 S-U
ECHO 8 V-X
ECHO 9 Y-Z
ECHO 0 RETURN
CHOICE /C 1234567890 /N

     IF %ERRORLEVEL%==1 GOTO 1
     IF %ERRORLEVEL%==2 GOTO 2
     IF %ERRORLEVEL%==3 GOTO 3
     IF %ERRORLEVEL%==4 GOTO 4
     IF %ERRORLEVEL%==5 GOTO 5
     IF %ERRORLEVEL%==6 GOTO 6
     IF %ERRORLEVEL%==7 GOTO 7
     IF %ERRORLEVEL%==8 GOTO 8
     IF %ERRORLEVEL%==9 GOTO 9
     IF %ERRORLEVEL%==10 GOTO 10

:1
ECHO 1 CASTLEVANIA - ARIA OF SORROW
ECHO 2 CASTLEVANIA - CIRCLE OF THE MOON
ECHO 3 CASTLEVANIA - HARMONY OF DISSONANCE
ECHO 0 RETURN
CHOICE /C 1230 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Castlevania - Aria of Sorrow.gba"
 IF %ERRORLEVEL%==2 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Castlevania - Circle of the Moon.gba"
 IF %ERRORLEVEL%==3 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Castlevania - Harmony of Dissonance.gba"
 IF %ERRORLEVEL%==4 GOTO GBA
EXIT
)

:2
ECHO 1 DRAGON WARRIOR MONSTERS
ECHO 2 DRAGON WARRIOR MONSTERS 2 - COBI'S JOURNEY
ECHO 3 DRAGON WARRIOR MONSTERS 2 - TARA'S ADVENTURE
ECHO 0 RETURN
CHOICE /C 1230 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Dragon Warrior Monsters (USA).gbc"
 IF %ERRORLEVEL%==2 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Dragon Warrior Monsters 2 - Cobi's Journey (USA).gbc"
 IF %ERRORLEVEL%==3 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Dragon Warrior Monsters 2 - Tara's Adventure (USA).gbc"
 IF %ERRORLEVEL%==4 GOTO GBA
EXIT
)

:3
ECHO 1 GACHASTA! DINO DEVICE 2 DRAGON
ECHO 0 RETURN
CHOICE /C 10 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Gachasta! Dino Device 2 Dragon (J).gba"
 IF %ERRORLEVEL%==2 GOTO GBA
EXIT
)

:4
ECHO 1 KEITAI DENJUU TELEFANG - SPEED
ECHO 2 KEITAI DENJUU TELEFANG 2 - POWER
ECHO 3 LIL' MONSTER
ECHO 0 RETURN
CHOICE /C 1230 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Keitai Denjuu Telefang - Speed Version (Japan).gbc"
 IF %ERRORLEVEL%==2 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Keitai Denjuu Telefang 2 - Power Version (J).gba"
 IF %ERRORLEVEL%==3 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Lil' Monster (USA).gbc"
 IF %ERRORLEVEL%==4 GOTO GBA
EXIT
)

:5
ECHO 1 MEDABOT - METABEE
ECHO 2 MONSTER RANCHER ADVANCE
ECHO 3 MONSTER RANCHER ADVANCVE 2
ECHO 4 MONSTER RANCHER CARD BATTLE
ECHO 5 MONSTER RANCHER EXPLORER
ECHO 6 NETWORK BOUKENKI BUGSITE - BETA
ECHO 0 RETURN
CHOICE /C 1234560 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Medabots - Metabee Version (E).gba"
 IF %ERRORLEVEL%==2 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Monster Rancher Advance (U).gba"
 IF %ERRORLEVEL%==3 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Monster Rancher Advance 2 (U).gba"
 IF %ERRORLEVEL%==4 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Monster Rancher Card Battle (USA).gbc"
 IF %ERRORLEVEL%==5 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Monster Rancher Explorer (USA).gbc"
 IF %ERRORLEVEL%==6 "C:\Emuladores\VisualBoyAdvance\VisualBoyAdvance.exe" "C:\Emuladores\VisualBoyAdvance\ROMs\Network Boukenki Bugsite - Beta Version (Japan).gbc"
 IF %ERRORLEVEL%==7 GOTO GBA
EXIT
)

:10
GOTO MENU
)

:SNES

ECHO ------Choose Game------
ECHO 1 A-C
ECHO 2 D-F
ECHO 3 G-I
ECHO 4 J-L
ECHO 5 M-O
ECHO 6 P-R
ECHO 7 S-U
ECHO 8 V-X
ECHO 9 Y-Z
ECHO 0 RETURN
CHOICE /C 1234567890 /N

     IF %ERRORLEVEL%==1 GOTO 1
     IF %ERRORLEVEL%==2 GOTO 2
     IF %ERRORLEVEL%==3 GOTO 3
     IF %ERRORLEVEL%==4 GOTO 4
     IF %ERRORLEVEL%==5 GOTO 5
     IF %ERRORLEVEL%==6 GOTO 6
     IF %ERRORLEVEL%==7 GOTO 7
     IF %ERRORLEVEL%==8 GOTO 8
     IF %ERRORLEVEL%==9 GOTO 9
     IF %ERRORLEVEL%==10 GOTO 10

:1
ECHO 1 ACTRAISER
ECHO 2 ALADDIN
ECHO 3 ALIEN 3
ECHO 4 BLACKTHORNE
ECHO 0 RETURN
CHOICE /C 12340 /N   
(IF %ERRORLEVEL%==1 "C:\Emuladores\SNES9X\snes9x.exe" "C:\Emuladores\SNES9X\Roms\ActRaise (U).smc"
 IF %ERRORLEVEL%==2 "C:\Emuladores\SNES9X\snes9x.exe" "C:\Emuladores\SNES9X\Roms\Aladdin (USA).sfc"
 IF %ERRORLEVEL%==3 "C:\Emuladores\SNES9X\snes9x.exe" "C:\Emuladores\SNES9X\Roms\Alien 3 (USA).sfc"   
 IF %ERRORLEVEL%==4 "C:\Emuladores\SNES9X\snes9x.exe" "C:\Emuladores\SNES9X\Roms\Blackthorne (USA).sfc"
 IF %ERRORLEVEL%==5 GOTO SNES
EXIT
)

:10
GOTO MENU
)

1276.

Solve : copy folder with latest time stamp using batch file?

Answer»

Hello,

I am a new user trying to use batch files for the first time. I am trying to create a batch file that will detect the folder with the latest time stamp, copy the entire folder and paste into another folder. The batch file will run everyday as new folders are added on a daily basis.

The folders are located on a network drive and I have been having trouble with the path as well.

I have been using the code below but it hasn't been working in my favor. Any help would be appreciated. Thanks!

echo off

set source=\\network_path\test
set dest= \\network_path\test2
pushd "%source%"
for /f "tokens=*" %%G in ('dir *.* /b /a-d /od') do SET newest=%%G

copy "%newest% "%dest%"
popd
cmd /k
When variables are set inside a do loop, delayed expansion is needed to access them outside the loop:

Code: [Select]echo off
setlocal enabledelayedexpansion

set source=\\network_path\test
set dest= \\network_path\test2
pushd "%source%"
for /f "tokens=*" %%G in ('dir *.* /b /a-d /od') do SET newest=%%G

copy "!newest!" "%dest%"
popd
cmd /k

Happy Coding  Thanks for your reply Sidewinder. Would you be able to help me with another question I had about my code? I need to copy the folder with the latest timestamp on it including all the sub folders in that folder. I think I need to MAKE changes to this part of the code ('dir *.* /b /a-d /od').

Would you know how to alter it to include copying over folders and the subfolders?

Thanks!The dir command would need to select directories and not files [change the /a switch]. Also xcopy would be used instead of copy. Something like this might be helpful:

Code: [Select]echo off
setlocal enabledelayedexpansion

set source=\\network_path\test
set dest= \\network_path\test2
pushd "%source%"
for /f "tokens=*" %%G in ('dir *.* /b /ad /od') do SET newest=%%G

xcopy /s /e /i "!newest!" "%dest%"
popd
cmd /k

Hope This Helps  Thanks for your quick reply Sidewinder. This worked perfectly but the only problem I am facing is that the code is copying all the folders within the "test" folder and not the "test" folder itself.

Is there a way we can copy the "test" folder and the sub folders within it?

Thank you for your continued help!I'm a bit confused, but onward and upward. The test in the source variable is not a folder but a share name. You can direct the data on the dest variable

Something like this:
Code: [Select]echo off
setlocal enabledelayedexpansion

set source=\\network_path\test
set dest=\\network_path\test2
pushd "%source%"

for /f "tokens=*" %%G in ('dir *.* /b /ad /od') do SET newest=%%G

xcopy /s /e /i "!newest!" "%dest%\!newest!"
popd
cmd /k

Note: As written above on the xcopy command, the top level folder will be the name of the folder you just copied. If you want the top level folder to be something specific, you can hardcode the value in place of !newest!, like "%dest%\test"

Keep Us Posted  Thanks for your reply. LET me try explaining exactly what I need my code to do. The "test" folder has various folders in it which correspond with today's date. A new folder is added everyday with the current date as its filename. Here is an example of what the inside of the "test" folder looks like:

19Feb2020
18Feb2020
17Feb2020
and so on...

The code I am trying to create needs to pick up the folder with the latest timestamp (i.e. 19Feb2020) and paste it into folder "test2".

So far, the code is copying all the contents inside "19Feb2020" and pasting it into "test2". I need the code to copy the folder (19Feb2020), including the sub folders, and paste it into "test2".

Since the filename changes everyday, I am using this strategy to detect the latest file and paste it into the required path. Please let me know if you can think of another approach to this problem or any ALTERATIONS to the pre-existing code.

Thank you very much!

You are using the Universal NAMING Convention (UNC) for both the source and dest variables. Not a problem but they are different than local folder paths. The \\network_path in both variables is not a folder name but the MACHINE name of the network device. test and test2 in each of the variables is also not a folder name but the sharename used to access the device or when mapping the remote drive to a local drive letter. If you want everything to be copied to the test2 folder, you will have to create it yourself. XCOPY will do this for you if you add test2 to the dest variable on the xcopy instruction.

Code: [Select]echo off
setlocal enabledelayedexpansion

set source=\\network_path\test
set dest=\\network_path\test2
pushd "%source%"

for /f "tokens=*" %%G in ('dir *.* /b /ad /od') do SET newest=%%G

xcopy /s /e /i "!newest!" "%dest%\Test2\!newest!"
popd
cmd /k

You may have to tweak the xcopy parameters, but this should work if my interpretation of your request is correct.

 You are a genius Sidewinder. This works perfectly! I have been trying to figure this out for the past week. Thank you for your help!  + 1 Sidewinder ! !There is no need for using delayed expansion as the variable is used after the FOR command has completed.

1277.

Solve : DOS does not see modem?

Answer»

We are running Windows 98 on a Novell network, and need to use a DOS program to dial into a voice mail system to trouble shoot it. I have checked the settings, and the COM ports are correct, and I can reach the modems from windows, but when I try to reach them from DOS nothing happens. I did an echo atdt12345 > Com1  and it would just give me a DOS prompt.Here, check this out: http://www.gemtree.com/download/terminal.exeYou might want to also use HyperTerminalThere are probably still places where you can get simple DOS terminal programs like ProComm, Omen, or RoboCom to use in DOS and ACCESS your modems.

You can write a text file and send it to your modem

echo dialin.txt > com1:

and it might work BETTER. But then you have nothing to follow up your initial opening of the modem with. The modem will be spraying NUL: with whatever characters the station at the other end tries to send as login INFO.

1278.

Solve : HIt says "Program too big to fit in memory.&q?

Answer»

;Hey!   First time here. I just have a problem wtih MS-DOS. Well, my friend downloaded a game off the internet call Sims Superstar   and he called me for help to work the program.  :-/ You have to open it in DOS. I click on it and a black window comes up and it shows the message Program to big to fit in memory for a split SECOND.  :-/ :-/ I click on it some more and it still displays the same message. Is there a way to open the program with another way except for DOS?   Maybe you can help me edit some info to work the program. THANKS! Try upgrading your memor, or using the keyboard interface instead of mouse interface.What does that mean? How do i do those THINGS? I have no idea about this, but try using extended memory, or run emm386.exeThe following should be part of your Config.SYS file:

device=c:\WINDOWS\himem.sys
dos=high, umb
device=c:\windows\emm386.exe noems

files=65
buffers=64
stacks=9,256
fcbs=10,6

lastdrive=z

devicehigh=c:\windows\setver.exe
devicehigh=c:\cdrom\oakcdrom.sys /d:mscd001


(I'm assuming your CDROM driver is in a directory called CDROM on C: root, use the directory you have it in and the appropriate driver name.)

In your Autoexec.BAT, the resident drivers should be PRECEDED by LH:

echo off
path ;
c:\antivir\antivir.exe /dosscan /autofix
LH c:\cdrom\mscdex.exe /d:mscd001 /m:12
LH c:\audio\au3drv.exe /parameters
LH c:\tablet\tabletdvr.exe
LH c:\speech\speechcard.exe
path c:\windows;c:\windows\command;c:\;c:\antivir;c:\speech;
prompt $p$g
set temp=c:\windows\temp
ver


These are SAMPLE files, put your appropriate drivers and the like in. An antivirus 'boot scan' pass is not resident; resident programs are loaded into Upper Memory with this layout and DOS is loaded into both High Memory and Upper Memory to leave plenty open for your apps. The bootup is based on DOS 7 in Win9x, if you are using earlier Windows you have a directory C:\DOS vice C:\Windows\Command.

1279.

Solve : Batch file and rename junctions?

Answer»

Hello everyone,

Is it possible to rename a junction with patch or powershell. I'm trying to rename the C:\ProgramData\Application Data folder.

Code: [Select]REN "C:\ProgramData\Application Data" "Application Data1"
But it doesn't WORK. and when I run /dir is doesn't show up but /dir /a it shows that Application Data is a junction and not a folder. So I was wondering if there is a way to do it. Thanks in advanceI would highly advise against this as many programs now store their configuration files in this directory.If you rename it WINDOWS will be borked...Well due to a workaround my company has found the renaming the folder fixes an install error I'm getting when installing a cisco program.The junction point is itself primarily for backwards compatibility. Vista changed the arrangement of folders and where special folders were. The short of it is that in XP the special folder was shared with a few other special folders, such that "Application Data" was available from that location, and so programs expected to be able to use \Application Data but in Vista that folder no longer existed because the special folder was moved to it's own location. To fix compatibility problems, the junction point C:\ProgramData\Application Data was added which points back at C:\ProgramData to resolve that problem.

As for renaming it, The junction point has security permissions set on it. You'll want to first unset the Hidden and System attributes, then edit the security permissions in File Explorer to remove the deny entry denying everyone List contents/Read Data permissions. This should allow the rename to work, then you can add the security permission back and reset the hidden and system attributes.

Thanks for your help BC, it looks like I am unable to edit any of the permissions for the EVERYONE group or any group for that matter. Even if I CHANGE the owneryou will likely need to use a TOOL like psexec to elevate to the localsystem account, then use icacls to remove the deny permissions.Thanks so much for your help. I really appreciate it

1280.

Solve : Command Line to get the PRODUCT ID of Dell/Acer notebooks??

Answer»

Hello,

I am talking about the PRODUCT ID (PID) of notebooks, this alpha-numeric number defining a unique hardware configuration.
I am not talking about the SERIALNUMBER: the very unique machine ID.
I am not talking about the MODEL: a brand's family name, including a many variants of hardware configurations.

I MEAN:
- PID is the hardware configurations ID, defining what components are inside the NOTEBOOK).
- PID could be CALLED MPN (Manufacturer Part Number) or SKU number (for HP notebooks).

Online stores could show the PID as the Manufacturer Reference.
Googeling a MODEL: you will find many notebooks with different configurations (different PID).
Googeling a PID: you will find many notebooks with the same hardware configuration (same PID).

EXAMPLE 1: HP Spectre x360 13-aw0724nz Convertible (13.3 ", 512GB SSD, Poseidon Blue)
- MODEL: HP Spectre x360 Convertible 13-aw0xxx
- PRODUCT ID: 8NH47EA#UUZ
- SERIALNUMBER: 5CD9497LH0

EXAMPLE 2: ASUS ZenBook S13 UX392FN-AB009T, Intel i7-8565U, (13.90", 1TB SSD NVMe, 16GB)
- MODEL: ZenBook UX392FN
- PRODUCT ID: 90NB0KZ1-M00220
- SerialNumber: K6N0CV04234624C

For HP notebooks, PID can be found using this DOS Command Line: wmic csproduct get skunumber
Code: [Select] 8NH47EA#UUZ
For ASUS notebooks, PID can be found using this Command Line: wmic computersystem get oemstringarray
Code: [Select] {"kPJ-+7X7+EfTa","jTyRUBSNi7Ydf","fCrOzJ6x1i-eh"," ","90NB0KZ1-M00220"}PID is: 90NB0KZ1-M00220

What is the DOS Command Line to get the PID of Dell notebooks?
What is the DOS Command Line to get the PID of ACER notebooks?

Thanks and regardsNobody will answer because they do not understand what your want.
From Google:  (https://support.google.com/merchants/answer/160161?hl=en)
Quote

About unique product identifiers

Unique product identifiers define the product you're selling in the global marketplace. They uniquely distinguish products you are selling and help match search queries with your offers. Unique product identifiers are assigned to each product by the manufacturer, so if you sell the same product as another retailer, the UPIs will be identical.

Common unique product identifiers include Global Trade Item Numbers (GTINs), Manufacturer Part Numbers (MPNs), and brand names. Not all products have unique product identifiers. However, if your product does have one, especially a GTIN, providing it can help make your ADS richer and easier for users to find. If your product doesn’t have a UPI, you’ll tell us so in your product data.

This article explains the unique product identifiers you may have to provide, how to troubleshoot issues with your identifiers, and what to do if you don't have them.
...
Who told you that DOS would give it?  It is s not a DOS thing.

Who wants to know? If the DEVICE is yours, you should already know.

Did you steal a laptop and want pretend it is yours? My resown for saying that is the fact that so many come here thinking we have secret INFORMATION about how to hack a computer. But you are not doing that - Right?

We will help you if we understand what you need. Tell us who needs to know.
For ACER notebooks, the PRODUCT ID (SKU) is a left sub-string of its SerialNumber. So, the DOS command line is:
wmic bios get serialnumber
Code: [Select]NXH62EZ00794700B346600
The PID is: NX.H62EZ.007

Product ID is well described here: https://youtu.be/_N8BfdCvMRgTake the 10 left characters (of the SN) and add dots. PID is NX.H62EZ.007
1281.

Solve : Batch program seems to be looping endlessly?

Answer»

Created a batchfile that seems to be entering an endless loop and am not sure why.
Would like someone to explain what is wrong here, and since I am terrible at this I believe, don't quote me, but it is probably a no-brainer for some of you!!

menu6.bat
Code: [Select]echo off
color 0a
title test
GOTO Main

:Main
cls
echo.
echo WIPE Free Space on selected drive:
echo.
cmdMenuSel f870 "Wipe free space on drive C" "Wipe free space on drive E" "Exit"
if %ERRORLEVEL% == 1 GOTO DRIVEC
if %ERRORLEVEL% == 2 GOTO DRIVEE
if %ERRORLEVEL% == 3 GOTO EXIT
GOTO Main

:EXIT
cls
cmdMenuSel f870 "Confirm" "Cancel"
if %ERRORLEVEL% == 1 EXIT
if %ERRORLEVEL% == 2 GOTO Main
GOTO EXIT

:DRIVEE
cd %windir%\system\Sysinternals
CLS
ECHO Pressing ENTER will wipe(1 pass) the free space on drive e:
pause
call sdelete -c -z e:
GOTO Main

:DRIVEC
cls
time
echo.
date
echo.
echo By iONic
GOTO Main
The DRIVEC loop works but the DRIVEE loop fails after performing the function.


menu5.bat
Code: [Select]Echo off
:TOP
color 0b
Mode 70,25
Title %~n0
Batbox /h 0

:Loop
Call Button  20 4 "Wipe free space on drive C" 20 8 "Wipe free space on drive E" 25 12 "Exit the program" # Press
Getinput /m %Press% /h 70

:: Check for the pressed button
if %errorlevel%==1 (GOTO DRIVEC)
if %errorlevel%==2 (GOTO DRIVEE)
if %errorlevel%==3 (exit)
goto Loop

:DRIVEC
cd %windir%\system\Sysinternals
CLS
ECHO.
ECHO Pressing ENTER will wipe(1 pass) the free space on drive C:
ECHO.
pause
call sdelete -c -z c:
GOTO Loop

:DRIVEE
cd %windir%\system\Sysinternals
CLS
ECHO.
ECHO Pressing ENTER will wipe(1 pass) the free space on drive E:
ECHO.
pause
This one fails after successfully executing but end up in a endless loop with an ERROR "button is not recognizes as an internal or external command"

Your help would be greatly appreciated.

Have you ever done batch files before?
Do you really understand this:
Code: [Select]if %ERRORLEVEL% == 3 GOTO EXIT
It might mean something you did not expect.
Do you program is some other language? Quote from: Geek-9pm on February 10, 2020, 05:19:31 PM

Have you ever done batch files before?
Do you really understand this:
Code: [Select]if %ERRORLEVEL% == 3 GOTO EXIT
It might mean something you did not expect.
Do you program is some other language?


Told you I was bad at this. As far as Code: [Select]if %ERRORLEVEL% == 3 GOTO EXITin the first batch file if i select 3 and press enter the batch file will begin executing at :EXIT
What follows is merely conformation to exit the batch file.In other languages the IF state rests fir a deterministic truth has has one meaning.
In BATCH, the error level is more like a maybe test.
I is like asking "How bad was the error?" The answer might not be a direct specific answer. Instead, it rates the error on a scale of bad to worse.
Here I am not going to use exact syntax. The is not the point.

Q. "Hey batch, how bad was the error. As much as a one?
A. if error-level = 1 "Yeah, I can say that it would be.
Q. "Hey batch, how bad news in error. As much as a two?
A. if error-level = 2 "Yeah, I can say at least a 2.".
Q. "Hey batch, how high was the error. MAYE a three?"
A. if error-level = 3 "I will say thee, if not more."
Q. "Hey batch,  did you get error. Up to four?"
A. if error-level = 4 "Four for sure, less I don't see."

Get it? READ over the examples is samples in the tutorials.
BATCH is not like any other task control tool. 
In your :DRIVEE label you change the current directory, but you do not change it back before you return to MAIN, so I'd wager it cannot find cmdmenusel anymore so you get stuck in an infinite loop.

I think that may be the case for your second batch file as well. I'd suggest that you use PUSHD to change to the sysinternals directory, and then before you return you use POPD.

I don't think Geek-9pm's COMMENTS are relevant, as he is thinking of a slightly different construct ("IF ERRORLEVEL X ") which is not what you are using.
I stand corrected. 
No excuse. Quote from: BC_Programmer on February 10, 2020, 06:46:33 PM
In your :DRIVEE label you change the current directory, but you do not change it back before you return to MAIN, so I'd wager it cannot find cmdmenusel anymore so you get stuck in an infinite loop.

I think that may be the case for your second batch file as well. I'd suggest that you use PUSHD to change to the sysinternals directory, and then before you return you use POPD.

I don't think Geek-9pm's comments are relevant, as he is thinking of a slightly different construct ("IF ERRORLEVEL X <command>") which is not what you are using.
Thanks, BC_Programmer, for the tip. It worked perfectly. I deleted the CD line and added the path to the call statement.
Can also work if I place the needed batch files in the same directory.
1282.

Solve : Need Help extracting specific data from a txt file and using it is cmd argument?

Answer»

All,

I have VIRTUALLY no idea how to write batch files and I have been searching the internet for help with this. 

I need to extract data from a txt file and use that data in a command line argument.  Below is an example of the data I need to extract.  The bold data is what I need.

NUMBER - 12345
Version - 1.02.03.4567
NAME - SOFTWARE name
Status - Upgrade completed successfully
Message - success
TIMESTAMP - 2019-12-11 17:12:45.188

I then need to use the extracted data in a command like this.

C:\util\someprogram.exe  -n 12345 -v 1.02.03.4567 -p Patch1 -d 2019-12-03 -m success -s “software upgraded successfully….”

I have this so far but it includes the dash before the data I need except for the last line because I am having to use the 3rd token.

FOR /F "tokens=3* delims= " %%i in (message.txt) do echo %%i %%j

Any help would be appreciated


Where are you getting this information from? ( Registry? or some prior executed program that assigns a number etc)

Quote

Number - 12345
Version - 1.02.03.4567
Name - Software name
Status - Upgrade completed successfully
Message - success
Timestamp - 2019-12-11 17:12:45.188
This data is in a txt file that is created by another program. Basically the upgrade itself will create this text file. Use tokens 1* with the dash as the delimiter, for each line, and use the * token for your fields, all except the last (hint: it starts "Timestamp") where you do another for /f on the second token, using 1* with the space as the delimiter, and take the first token.

(1) input.txt
Number - 12345
Version - 1.02.03.4567
Name - Software name
Status - Upgrade completed successfully
Message - success
Timestamp - 2019-12-11 17:12:45.188

(2) batch script
echo off
set filename=input.txt
for /f "tokens=1-2* delims= " %%A in (' type "%filename%" ^| find "Number"    ') do set number=%%C
for /f "tokens=1-2* delims= " %%A in (' type "%filename%" ^| find "Version"   ') do set version=%%C
for /f "tokens=1-2* delims= " %%A in (' type "%filename%" ^| find "Name"      ') do set name=%%C
for /f "tokens=1-2* delims= " %%A in (' type "%filename%" ^| find "Status"    ') do set status=%%C
for /f "tokens=1-2* delims= " %%A in (' type "%filename%" ^| find "Message"   ') do set message=%%C
for /f "tokens=1-3 delims= "  %%A in (' type "%filename%" ^| find "Timestamp" ') do set mydate=%%C
echo number:  %number%
echo version: %version%
echo name:    %name%
echo status:  %status%
echo message: %message%
echo mydate:  %mydate% 

(3) script output
number:  12345
version: 1.02.03.4567
name:    Software name
status:  Upgrade completed successfully
message: success
mydate:  2019-12-11thank you.  This worked perfectly.
1283.

Solve : How to get all key/value from WMIC command??

Answer»

On my Asus ZenBOOK S13 UX392FN, this command: wmic computersystem GET systemskunumber outputs this:
Code: [Select]SystemSKUNumber
and this one: wmic computersystem list /format:list GIVE me this:

Code: [Select]AdminPasswordStatus=3
AutomaticResetBootOption=TRUE
AutomaticResetCapability=TRUE
BootOptionOnLimit=
BootOptionOnWatchDog=
BootROMSupported=TRUE
BootupState=Normal boot
Caption=ZENS2
ChassisBootupState=3
CreationClassName=Win32_ComputerSystem
CurrentTimeZone=60
DaylightInEffect=FALSE
Description=AT/AT COMPATIBLE
Domain=WORKGROUP
DomainRole=0
EnableDaylightSavingsTime=TRUE
FrontPanelResetStatus=3
InfraredSupported=FALSE
InitialLoadInfo=
InstallDate=
KeyboardPasswordStatus=3
LastLoadInfo=
Manufacturer=ASUSTeK COMPUTER INC.
Model=ZenBook UX392FN_UX392FN
Name=ZENS2
NameFormat=
NetworkServerModeEnabled=TRUE
NumberOfProcessors=1
OEMStringArray={"kPJ-+7X7+EfTa","jTyRUBSNi7Ydf","fCrOzJ6x1i-eh"," ","90NB0KZ1-M00220"}
PartOfDomain=FALSE
PauseAfterReset=-1
PowerManagementCapabilities=
PowerManagementSupported=
PowerOnPasswordStatus=3
PowerState=0
PowerSupplyState=3
PrimaryOwnerContact=
PrimaryOwnerName=sam
ResetCapability=1
ResetCount=-1
ResetLimit=-1
Roles={"LM_Workstation","LM_Server","NT","Potential_Browser","Master_Browser"}
Status=OK
SupportContactDescription=
SystemStartupDelay=
SystemStartupOptions=
SystemStartupSetting=
SystemType=x64-based PC
ThermalState=3
TotalPhysicalMemory=16985055232
UserName=ZENS2\sam
WakeUpType=6
Workgroup=WORKGROUP
Why the key SystemSKUNumber is missing in the output of the second command ?
How to find the missing keys/values from those Command Line?
Code: [Select] wmic CPU list /format:list
 wmic bios list /format:list
 wmic csproduct list /format:list
 wmic BASEBOARD list /format:list
 wmic diskdrive list /format:list
 wmic computersystem list /format:list
Thank and regardsC:\Users\Mike>wmic computersystem get systemskunumber
SystemSKUNumber
7200-2004A

C:\Users\Mike>wmic csproduct list /format:list


Description=Computer SYSTEM Product
IdentifyingNumber=CM020009-032
Name=
SKUNumber=
UUID=03AA02FC-0414-056D-2506-C00700080009
Vendor=ZOOSTORM
Version=7200-2004A
To get more (maybe all) keys/values, i got this answer on another forum:

Code: [Select]wmic computersystem get * /format:list
Just replace "list" by "get *"

1284.

Solve : Merging tab delimited fields across two files?

Answer»

Howdy,

New member here and recently started working with some batch scripting (needs to be used on old XP machines sometimes). So far I've gotten a pretty good handle but I've run into a situation that I'm having a hard time understanding. I've read some other threads here and AROUND the internet but am still stuck.

Basically, I'm trying to use tokens to merge the information from two files with tab delimited info into one. Any help on how to get to where I need to go would be greatly appreciated. An example of my situation below:

FileA.txt (SQL query OUTPUT)

HOSTNAME   MacAddress   DEVICE   Type   LastUpdateDate
---------   ----------   ----   ----   --------------
VR702386   00CE39CA6B7C   Example Unit 1   active   2019-11-22 17:12:34.600
SJ180047   B8AEED7269F9   Example Unit 2   not active   2020-02-05 08:18:47.917
UJ560066   003018CD200E   Example Unit 3   not active   2020-02-05 04:33:51.457

FileB.txt (IP address ping output)

VR702386   10.10.2.204

Desired Output

HOSTNAME   IP Address   MacAddress   Device   Type
VR702386   10.10.2.204   00CE39CA6B7C   Example Unit 1   active
SJ180047   Off Network   B8AEED7269F9   Example Unit 2   not active
UJ560066   Off Network   003018CD200E   Example Unit 3   not active

Really, the most important thing here is that I can include the IP address where applicable and that everything remains tab delimited. Header formatting isn't necessarily a big concern to me but is a bonus.

If a unit cannot be pinged by hostname, it currently does not output anything to FileB.txt. Because of this, I would like to be able to INDICATE that any hostnames from FileA.txt without a corresponding IP address in FileB.txt cannot be reached ("Off Network" in my example output). Again, any help here would be awesome if this is even possible with a batch script. I'm stumped. Thanks!

1285.

Solve : CMD window doesn't close after batch script executes?

Answer»

I call several batch SCRIPTS from a master batch script (that I USE for maintenance) without any issue but there is this one script that will not exit when it's done running and I don't know why.  When I simply RUN the script it does exactly what I expect it to do - it executes and then exits when it is done running (CMD window closes).  When I call the script from my master script it executes (in a separate window, which is what I want) but its CMD window doesn't close. 

I call all my batch scripts like this:  START /wait Call "

1286.

Solve : Custom File Names Based on Folder Names, possible??

Answer»

Hi,

I have a file directory with several folders each with a unique FOLDER name. Within each folder is an Excel file.


How would a I rename each .xlsx file as follows: FOLDERNAME & "RECON P1".xlsx

I've looked online but can only find code and examples on how to replace PARTS of a file name but nothing LIKE what I require.

Would appreciate any information / assistance.

Many thanks.

1287.

Solve : Topic: Batch file to rename basted on other filename before move new dest.?

Answer»

Like to CHANGE my Batch file from rename/stripping filename (today below) to COPY the filename complete from an existing movie file (which can be .avi, .mov, .mp4) which always get dropped as pair in a folder under “Temp” before I move the JPEG-file away.

echo off
setlocal enabledelayedexpansion
set "sourcepath=C:\Temp"
set "folderpath=C:\master"

cd /d %sourcepath%
for /f %%a in ('dir /b "*.jpg"') do (
    set "fname=%%~na"
    ren "%%a" "!fname:~0,-9!.jpg"
)

for /F "delims=" %%a in ('dir /b /od "%sourcepath%\*.jpg"') do (
   set "youngest=%%a"
   move /y "%sourcepath%\!youngest!" "%folderpath%"
)
endlocal

Example COULD be:
C:\Temp\name1
09010203.mp4 and test.jpg, where the JPEG should change filename to 09010203.jpg, before I move it.

1288.

Solve : FFmpeg combines videos without re-encoding?

Answer»

Take MP4 as the video format to do operations.
Step 1: First of all, put all video files to be combined in one file folder and name it MP4;
Step 2: Then visit ffmpeg.zeranoe.com. In the "Builds" option, download FFmpeg Static on your COMPUTER;
Step 3: After that, get into this MP4 file and open the "bin" file folder. You need to copy the ffmpeg.exe file to the MP4 file folder;
Step 4: Next, please right-click the Windows icon or press Windows + R on the keyboard and type cmd.exe to open Command Prompt on your computer;
Step 5: After entering the Command Prompt WINDOW, you ought to change the path of the MP4 file folder;
Step 6: Now, type command: (for %i in (*.mp4) do echo file '%i') &GT; mylist.txt and press Enter. Then you will get a mylist.txt file that covers all MP4 files on this folder;
Step 7: Lastly, type command: ffmpeg -f CONCAT -i mylist.txt -c copy output.mp4 to start combine videos with FFmpeg. If nothing unexpected happens in the process, these videos will be quickly merged into a file named output.mp4 in the MP4 file folder.
If you think this is a little complicated, you can try an easy FFmpeg alternative - Joyoshare Video Joiner.

1289.

Solve : how to select folder with latest time stamp using batch script?

Answer»

Hello everyone,

I am trying to CREATE a batch file that will essentially look into a specific folder to check for missing files. However, the folder changes everyday and a NEW folder is created everyday with PREVIOUS business day (t-1) as the folder name. Hence, I am trying to create a dynamic batch script which will select the folder with the latest date as its fodlername. Here is an example of what the path to the folder would look like:
C:\Users\UserA\Ad_Hoc\25Feb2020\Folder_A\File_A

The folder name in bold is what would change everyday and everthing else stays consistent. Is there a WAY to make the path dynamic in terms of the changing folder name?

Thanks!

1290.

Solve : Find a value in column 1 of a txt file and assign value in column 2 to a var?

Answer»

I have GETPCName.txt that contains two columns
007321182553 SP-ContriD
CNU2469BBG 6470B-194880
CNU2469B72 6470B-203019

I run the FOLLOWING batch file on a computer with s/n 007321182553 and it results in "There is hope!"

for /f "tokens=2 delims==" %%f in ('wmic bios get serialnumber /value ^| find "="') do set "PCSN=%%f"
ECHO %PCSN%

findstr /m "%PCSN%" GetPCName.txt
if %errorlevel%==0 (
echo There is hope!
)


What I want to after finding that STRING is assign "SP-ContriD" on that line to a variable that I can USE in the rest of the batch file.  How do I do that?This may help. A new variable (NewVar) is created with a value of SP-ContriD. The WMIC output was perfectly setup, only needed a set instruction to precede it.

Code: [Select]echo off

for /f "tokens=1" %%f in ('wmic bios get serialnumber /value ^| find /i "serialnumber"') do set %%f

for /f "tokens=1-2" %%i in (GetPCName.txt) do (
  if %%i==%SerialNumber% set NewVar=%%J
)

if %errorlevel%==0 (
  echo There is hope!
)

echo Variable NewVar has a value of %NewVar%

Happy Computing

1291.

Solve : How can I get the DVD device type into variable?

Answer»

Hello!
I need to determine whether the DVD device in the computer is DVD Writer or DVD reader
I do it through wmic cdrom where mediatype!='unknown' get mediatype
It returns
MediaType
DVD Writer

However, how can I put "DVD Writer" into variable?

I tried

wmic cdrom where mediatype!='unknown' get mediatype > tmpFile.txt
set /p data=
However the content of %data% is
■MRun this at the the CONSOLE. The variable %mediatype% will have the value DVD Writer

Code: [Select]for /f "TOKENS=* skip=2" %i in ('wmic cdrom where "mediatype!=\"unknown\"" get mediatype') do echo %mediatype%

Good luck.  Please disregard the previous post. When I returned to check it out, it failed. Sorry for any inconvenience. If I find a fix I will post any updated version.

 
OK, lets try Solution 2.0

The variable %mediatype% will have the value DVD Writer

Code: [Select]for /f "tokens=* skip=1" %i in ('wmic cdrom where "mediatype!=\"unknown\"" get mediatype') do if not defined mediatype set mediatype=%i

Good luck. 


Hi 
This how to fix your problem with a BATCH FILE :
The output of WMIC is unicode !
The trailing <CR> can be removed by passing the value through another FOR /F loop.
This also removes the phantom "blank" line (actually a <CR>)
Code: [Select]echo off
set "mediatype="
for /f "skip=1 delims=" %%a in ('wmic cdrom where "mediatype!=\"unknown\"" get mediatype') do (
for /f "delims=" %%b in ("%%a") do if not defined mediatype set "mediatype=%%~nb"
)

echo MediaType is : "%mediatype%"
pauseThe variable %mediatype% will have the value "DVD Writer"

1292.

Solve : sort paragraphs?

Answer» HELLO.
 USING Windows 10.
 I need to SORT paragraphs in a text document by the 2d LINE in the paragraph. Is there a command line sort command to do that?
   I did find a program called CMsort but don't SEE if it can sort paragraphs.
1293.

Solve : Batch expert needed file cannot be for looped because of first symbol?

Answer»

I'm having a bit of an issue in the LINK there is a text FILE and you will notice that first character is unknown symbol and after batch tries to for loop it only copies that first character and stops there.

Is there a way to tell batch to continue or to WARN him before that there is unknown symbol? or even delete it and proceed with the rest of file?

Link to text file:
https://easyupload.io/eknrri

Script:

Code: [Select]    :: TURN echo off
    echo off
   
    :: Enable extensions
    SETLOCAL EnableExtensions
    SETLOCAL EnableDelayedExpansion
   
    :: Set input file
    set "InputFile=index.txt"
   
    :: Set output file
    set "OutputFile=output.txt"
 
    :: Check if output file exits if it does delete it
    If Exist "%OutputFile%" Del "%OutputFile%"
   
    :: Loop through input file
    for /F "tokens=* delims=" %%A in ('Type "%InputFile%"') do (
        :: Set line equal to file text
        set line=%%A
   
        echo !line!
    )&GT;>"%OutputFile%"

1294.

Solve : Help needed with this batch file?

Answer»

Firstly I want to make it clear that I have no EXPERIENCE in this. Using Win 7 x64. I'm playing a game and somehow another program called Netlimiter is interfering with the game's online. With some experimentation, I figured out that if I close Netlimiter before starting the game, then start the game, then start that program again by Alt+Tab-ing to the DESKTOP -- then the game runs fine.

After this DISCOVERY, the next thing that came to my mind was to have a batch script that could do it automatically and save me the hassle. But as I said, I have no experience in batch scripts or even DOS commands. I have been searching the web for almost a day and came up myself with this script that seems to work. I have put the batch file in the game FOLDER.

Code: [Select]ECHO off

Taskkill /F /IM NLClientApp.exe

start Monopoly.exe

TIMEOUT /T 10 /NOBREAK

start /d "C:\Program Files\Locktime Software\NetLimiter 4\" NLClientApp.exe

But then there is one annoyance. When Netlimiter starts again(in system tray), it switches my game back to the desktop and then I have to manually click on the game window to go back into the game. Is there any way the above script can be modified so that either this can be prevented, or maybe switch the focus back to the game automatically?

I'd really appreciate any help. I hope I have explained this well enough.I don't know of any way to execute a batch file without it taking application focus.

However you might be able to do it with VBScript. See this thread for info that might help.

Quote from: nil on May 19, 2020, 05:25:24 PM

I don't know of any way to execute a batch file without it taking application focus.

However you might be able to do it with VBScript. See this thread for info that might help.
No, actually it's not the batch file taking focus. As you can see that I'm using it to run the game as well, thus it automatically switches to the game window. The issue is that in the last line where Netlimiter starts again in the system tray, my game window minimizes to desktop for whatever reason. I read that it only takes app focus if the app has a window which isn't the case here, so Idk why it's happening. But anyway, if somehow the focus could be brought back to the game, then that's all I'm looking for.Sorry, what I meant was, I don't know of any way to start a program from the command line (or a batch file) which can specify that the new program should not take focus.

However, VBS allows you to do that. So if you refactor your batch file as a VBScript, it might do what you want.

Ultimately however the application is going to decide whether it's focused or not. If there's code in Netlimiter that specifically takes control of application focus, you're probably just gonna have to live with it.
1295.

Solve : Batch to list if some folder is missing two especific files?

Answer»

Hi guys, I would like help to CREATE a batch script.

Here's my problem, I have a folder with many subfolders, and some of them need to have a certain image file:  "Cover.jpg", some of them have, but others are missing ... and there are hundreds of FOLDERS to check ... I managed to find this bat:

Code: [SELECT]echo off
for /d /r %%f in (*) do (
if not exist %%f\Cover.jpg (
echo %%f >>W:\HD\Cover_Missing.txt
)
)
The problem is that it returned many results, like parent folder.. then I wanted to improve it by placing the condition that in addition to having the file "Cover.jpg" having the file * .mp3 or * .m4a.. so the RETURN would be less to analyze ....

Could someone help me by doing ... I know very LITTLE about programming

Thank you!You can try with the command Where /?
Example :
Code: [Select]echo off
Set Source=%~dp0
Set Pattern=Cover.jpg *.mp3 *.m4a
Where /R %Source% %Pattern% /F
pause

1296.

Solve : access denied via batch?

Answer»

in windows 10...

Code: [Select]echo off
cd c:\
REN 1.hlp 1.txt
pause
When executed returns - access is denied, Press any key to continue.
Why?
How to fix?

both the batch file and 1.hlp file are in c:\Root directory protections. If you place those into a directory within C: such as at C:\Data it will likely work flawless. Everything you got going on should really be elsewhere but root of C: unless it absolutely needs to happen in root of C:

I think only way to get around the access denied in root of C: is to open the command shell as ADMINISTRATOR which should shut off the access denied issue as its a protection put in place by Microsoft to stop malicious changes from root of C:It does seem to be a privilege issue, but merely adding a new directory in C does not fix it.
in other  words...

Code: [Select]echo off
cd c:\TEST
pause
ren 1.hlp 1.txt
does not work for me(BAT file and 1.hlp moved to c:\test)
by changing the permission of the shortcut to "run as admin" results in a prompt to proceed and then it does run.
I will try this with the full batchfile and report back.Hi
You should run your batch as administrator to achieve your aim, so try like that instead :
Code: [Select]echo off
Title Renaming file
If [%1] NEQ [Admin] Goto RunAsAdmin
:MainScript
cd c:\
ren 1.hlp 1.txt
pause
Exit
::---------------------------------------------------------------------------------------------------
:RunAsAdmin
cls & color 0B & Mode 90,5
echo(
echo(            ===========================================================
echo(                  Please wait a while ... Running as Admin ....
echo(            ===========================================================
Powershell start -verb runas '%0' Admin & Exit
::---------------------------------------------------------------------------------------------------sounds good....will do this!
I'm all good. things are working well. Had to work my way thru all the IF statements that are needed to make sure some unforeseen fault did not occur such as duplicate files, WRONG file with wrong name...etc.

thanks

1297.

Solve : Batch File Q: Please Help Me!?

Answer»

This will probally seem like a stupid question to any experienced dos user, but I need to know if it is possible for a batch file to answer prompts in a program.  I want to create a batch file that will start a dos program (called rmovave) and answer the prompts so the program will run without me having to type in the same paramaters over and over.  The program, rmovave, will not accept an answer file or I'd fix it that way.  Maybe what I want to do isn't possible? It seems like it should be.  Please help me as I have several hundred files to run through this program (and three others after that!!).  Thanks.If you are using XP or 2000 try:
Code: [Select]
set /p var=promptstring


If you are using DOS or Win9x there is a nifty little utility. Answer ALLOWS you to prompt for user data and store it in the environment space. Each time it runs the environment variable is overwritten, so be sure to SAVE each value to your own variables. Put into a directory along your path and you can use it anywhere.

Hope this helps. Thanks for the help sidewinder.  I am using command prompt in windows xp.  You have to forgive me, I'm really new to using dos.  After I add your code should I put /p before each line of prompt?  Thanks again.Yes. Something like this:

Code: [Select]
set /p input=Enter NAME of input file:
set /p output=Enter name of output file:


You can then use the %input% and %output% variable names in your batch file.

Good luck. I TRIED what you told me to do but the /p lines don't answer the prompts in my program (rmovave).  I think I'm in a bit over my head.  I just learned what a .bat file is today.  I guess I have to run all hundred plus files I have manually.  My mistake, I misread your question. Some programs expect parameters on the command line. Some programs can read redirected input. Some programs will accept input thru the pipe and some programs can read an answer file. What program are you referring to?

The program is called Rectified Moving Average (rmovave for short).  I don't think it's very common.  I believe it's written in Pascal if this helps. I'm using it to smooth waveform files (people's heartbeats or ECGs) to isolate a certain part of the wave.  I know it will not accept an answer file.  Does that mean that my hope of creating a batch file to make my life easier is in vain?    I couldn't find any info on the net for your program. Does it not have any documentation about how to run it. I would think the program would take a command line parameter that points to the input file. You might be able to build a loop, processing each file thru your program.

If you could post how you run it from the command line, perhaps someone could find a solution.

Let us know. Okay, this is my last post of the day 'cause it's time to get on the subway and go home.  The program runs like this, step by step:
rmovave [starts program]
imput file?
output file?
sampling rate?
time constant to use?
signal ground?
start at what sec?
end at what sec?
I hope this answers your question.  I desperatly want to build that loop your talking about.  I spent the entire day answering these prompts over and over again.  All answers were the same with the exception of input and output file (obviously).  Thanks for your help.Since the program is calling for data, all that needs to be done is to redirect the STDIN device (the keyboard) to a file. And a little smoke and mirrors of course

Code: [Select]
echo off
for /f "tokens=1-2 delims=. " %%a in ('dir /b /s path\*.dat') do (
     echo %%a.%%b       > answer.dat
     echo %%a.out      >> answer.dat
     echo samplingrate >> answer.dat
     echo timeconstant >> answer.dat
     echo signalground >> answer.dat
     echo startsec     >> answer.dat
     echo endsec       >> answer.dat
     path\rmovave < answer.dat
     )


How does it work?

1) gets a list of all the input files; the *.dat is the filter. (please tell me they're in the same directory)
2) sets up responses to program queries
3) runs program using redirected STDIN device, the answer.dat file

Output files will have same name as input file with a .out extension. Change if need be.

You need to fixup path\ and *.dat Make sure the path\ points to the input and output files and the filter matches your input file extensions; Also put real values for sampling rate thru endsec and fixup the path\ to the rmovave program.

With any luck all your input files will be processed with no input from you.

Good luck. Not to nick sidewinders thunder but i found this ,and its up to you!>http://www.softtreetech.com/i24x7.htmThanks guys for all your help!  We're almost there, except for one problem.  My program (rmovave) doesn't like having the path ahead of the input and output file.  How can I alter sidewinder's code so that the path doesn't show up in the answer.dat file the batch file creates? I need to do this for both input and output.  You guys have been so helpful. Thanks again so much!  Remove the /s switch from the dir command:

Code: [Select]
for /f "tokens=1-2 delims=. " %%a in ('dir /b path\*.dat') do (


If you are running the batch file from the directory where the input files and the rmovave is located, you don't need any path\ info. The output files will also be placed in the same directory.

Hope this helps. IT WORKS!  Thanks so much sidewinder, you have no idea how much this helps me, along with everyone else in my office.  I'm going to try and add on to this file so that it will run the output through two more programs.  I'll probally have problems with that too, but now I have somewhere to start from.  Thanks again!One more question.  I'm trying to apply the same code to use with two more programs.  The programs are sample (downsamples the sample rate of the file ie. from 500Hz to 5Hz) and int2drl (converts files to double realtime precision format).  I've created batch files to do this as a test (EVENTUALLY I want to combine them all into one batch file) and I've run into some old problems.  I wrote the code out exactly the same, changed the values for input, changed the filter, and gave the answer file a new name.  Yet it doesn't want to use the .dat file to answer the program prompts as it so nicely does for rmovave.  Any ideas?  Thanks again!

1298.

Solve : window log files?

Answer»

hey guys i know that our data is being SEND to Microsoft in log file but don't know how to see that log file can some buddy help me to solve this PROBLEM. i am not talking about the log files present in the computer MANAGEMENT  but the log files which is being send to the Microsoft i have seen that log file in an CYBERSECURITY seminar please help me Hi 
Please can you POST the link where did you find that ? i mean the link of cybersecurity !
Thank you !

1299.

Solve : Boot installed MS-DOS from diskette?

Answer»

Hi!

I have installed MS-DOS 7.10.
Bootloader is overwritten by my choice.
I need to BOOT installed MS-DOS from diskette - simply start on diskette and reroute after boot begin to installed DOS on C:\
I tried it and no success - it looks like rerouted but also with full path commands it always reads files on floppy.

Needs it change %path% variable or anything similar?

Thank you for help.
MiroIs this an empty HDD ? ?  is it set to primary / active ? ?
Did you sys the C:drive if all above has been done ? ?Hi!

I'm sorry for delay.
It is drive with MS-DOS 7.10 on first partition.
SYS C: rewrites boot sector and I want to leave boot sector untouched (it was configured for second OS - OSX86, I know, you maybe don't believe, but works).
I need to start from floppy for this reason:
1. boot of OSX don't recognizes DOS, it is visible only as Foreign OS.
2. DOS from floppy starts, but it is REQ'd to run autoexec.bat again after DOS boot to have environment active.
3. floppy always runs autoexec.bat from itself, I need to switch to use autoexec.bat on C:\

MiroWell good luck to ya...you cant do it the way you want to with OSX.
All your issues you post here seem to have a common theme..."I wanna do what i can;t"...It's old Apple computer running OSX Tiger 10.4 with built-in floppy.
It is old OSX using yet supporting UniBin and it is for my hobby. DOS is my primary target.

I need to help only with DOS booting, nothing about Apple.
Both SYSTEMS working, I need to avoid starting DOS manually after skip loading some drivers.

Whole Q is in title.

Miro

1300.

Solve : Assign Variable for use by tokens statement in Windows 7 batch file?

Answer»

Hello,
hoping this is a simple question. I am working on a process for work...the overall path to a solution may not be the road I am currently on, but this is a learning experience regardless and so far I like where it's going. Quick explanation..

Want to run a batch file on .csv file(s) that will have varying column counts. Is there a way to read the header to determine how many columns are in this particular .csv file and assign that to a variable to be used by the tokens statement later in process? This is in Windows 7.

Here is what I have so far...

ECHO OFF
SETLOCAL
SET "sourcedir=C:\Users\trig\Desktop"
SET "destdir=C:\Users\trig\Desktop"
SET "filename1=%sourcedir%\Before.csv"
SET "outfile=%destdir%\After.csv"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 FOR /f "tokens=4delims=," %%x IN ("%%a") DO ECHO %%a
)
)>"%outfile%"

GOTO :EOF

FOR /f "tokens=4 is the piece I want to put a variable in..ie FOR /f "tokens=%numofcolums%

any help is much appreciatedHi 
Give a try for this example and tell me if this what you want or not ?
Code: [Select]echo off
Title Assign Variable for use by tokens statement
If /I [%~x1] NEQ [.CSV] (
Color 0C & echo(
echo      You should drag and drop a [".csv"] file over this script "%~nx0"
Timeout /T 5 /NoBreak>nul
Exit
)
setlocal EnableDelayedExpansion
set _comma=,
set count=0
set /p _line=<%1
Call :Count_Commas
echo( & color 0A
echo The file "%~nx1" contains !count! commas
set /a Tokens= !count! + 1
echo(
echo The num_of_colums in this CASE will be !Tokens!
echo(
pause
exit
::---------------------------------------------------
:Count_Commas
if [!_line:~0^,1!] equ [!_comma!] (
set /a count+=1
)
if [!_line:~1!] neq [] (
set _line=!_line:~1!
goto :Count_Commas
)
Exit /b
::---------------------------------------------------Thank you for the reply Hackoo and sorry for the late response.

If I understand your code correctly, the TOP section is basically calling the bottom and resetting the "count" variable to 0 for every file...the bottom section is doing the actual counting of the commas (counting how many columns)? Is this CORRECT?

Also, what does Line 5 - echo      You should drag and drop a [".csv"] file over this script "%~nx0" mean? drag and drop a .csv file?

For what it's worth, right now my Before.csv file looks like this -
Col1,Col2,Col3,Col4,Col5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
,,,,

1,2,3,4,5
1,2,3,4,5
and with the code I have in my original post, the After.csv file looks like this -
Col1,Col2,Col3,Col4,Col5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5

Which is perfect, but like I said, I want to count the number of columns on the fly, for as many .csv files as there may be in this folder at the time the batch file is run.

Kris