Search code examples
batch-filecmdwinpe

Is it possable to iterate all files in a directory and have assign a number to each file and wait for input in cmd script


I am attempting to automate a process using a batch script. I want to iterate all the files in a specific directory with a specific file extension (.gho) and do something with it.

I know I can get the file names with "dir /B *.gho" but I would like cmd to list each file name with a number and wait for input then pass file the name off to a variable so it can be combined with another variable containing a command to execute.

Example:

  1. WinXP.gho
  2. Win7.gho
  3. Win10.gho

What image would you like to use?

I know I can write something like this in VB.net but this is going to be used in a PE boot disk and from what I understand .net apps don't work in a PE without some work. Can someone point me in the right direction, once I know it can be done and what to look for I probably can figure out the rest myself.

Thanks in advance.


Solution

  • Assuming that findstr.exe resides in %SystemRoot%\System32 of your PE base OS, and the current working directory under which this script is running, holds your target .gho files, here's an example template you can use:

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    Set "ext=.gho"
    For /F "Delims==" %%G In ('"(Set #) 2> NUL"') Do Set "%%G="
    For /F "Tokens=1* Delims=:" %%G In ('Dir /B /A:-D "*%ext%" 2^> NUL ^| ^
     %SystemRoot%\System32\findstr.exe /E /I /L /N "%ext%"'
    ) Do Set "#%%G=%%H" & Echo( %%G.    %%H
    If Not Defined #1 (Echo No file matches, press a key to exit.
        Pause 1> NUL & GoTo :EOF)
    :Opt
    Set "opt="
    Echo(
    Set /P "opt=Enter the number for your chosen file>"
    Set "opt=%opt:"=%"
    Set # | %SystemRoot%\System32\findstr.exe /B /L "#%opt%=" 1> NUL || GoTo Opt
    SetLocal EnableDelayedExpansion
    For %%G In ("!#%opt%!") Do EndLocal & Set "opt=%%G"
    Echo(
    Echo( You Selected %opt%
    Pause
    

    As this is a template the extension on line 3 is replaceable with any other, as needed. Your own code would be written from line 18, (replacing the three example lines I included just to show you the result, now assigned to %opt%. Nothing else between those two lines should be modified.