Search code examples
windowsbatch-filecmdforfilesdism

Error when trying to store a file name into a variable (cmd)


Basically I wanna find a .wim file and want to know in which volume it is and what the name is.

This is my code:

@for %%a in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do @if exist %%a:\*.wim set IMAGEDRIVE=%%a
@echo The Image drive is: %IMAGEDRIVE%
@forfiles /P %IMAGEDRIVE%:\ /S /C "cmd /c set FILENAME=@FNAME"
@echo The File name is: %FILENAME%
@pause

Because i later wanna do this:

dism /apply-image /imagefile:%IMAGEDRIVE%:\%FILENAME%.wim /applydir:w:\ /Index:1

It correctly finds the Volume H where the image.wim file is. But it cant find anything when trying to get the name. The File is there I checked that already.

What am i doing wrong? Or is there a better way of doing it?


Solution

  • Your main problem is that cmd /c set FILENAME=@FNAME" executes the set command in a separate process that immediately exits and destroys the variable (it's only available in the child process opened by cmd /c but not in the calling parent process (where you need it).

    I would replace the forfiles command with another for loop:

    for %%a in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do for %%b in ("%%a:\*.wim") do set "imagefile=%%b"
    echo the File name is: %imagefile%