Search code examples
powershellbatch-filesubdirectory

Update file in each subdirectory with a specific name


I have a which pulls a file from a url using and then outputs/updates the file in a specific directory. But I have many of these directories, the only thing that changes about the path is numbers between \command\ and \setup\. How would I get it to put the file in every folder automatically?

Essentially I would like to output the downloaded text file in each of the install of that path.

Also how could I make it happen silently?

@echo off
echo !!! PRESS ANY KEY TO CONTINUE AND UPDATE!!!
pause

powershell -Command "Invoke-WebRequest http://example.com/log/read.txt" -OutFile C:\Users\Administrator\AppData\Roaming\base\command\234235234\setup\install\read.txt 2>NUL >NUL

echo !!! DONE NOW !!!
echo !!! YOU CAN RE-OPEN NOW !!!

Solution

  •  for /d /r "dirname" %%a in (*) do if /i "%%~nxa"=="install" echo %%a
    

    may be useful to you.

    Your requirement is unclear. Do you want to copy the file to the install subdirectories of ...\234235234\.. only, or of ...\*\... ?

    Replace dirname with the name of the starting directory, be it ...\234235234\.. or C:\Users\Administrator\AppData\Roaming\base\command and the command I have shown will report all of the install directories contained under dirname. All you need then do is to change the echo to an appropriate copy command - see copy /? from the prompt. You can suppress copy's responses by appending >nul 2>nul (suppress messages and suppress error messages)

    for /d /r with * as the list element will process a list of all subdirectories starting at the nominated directory. The if command selects only the leaf directories that match install in either case (/i)


    Since

    for /d /r ...
    

    does nor detect hidden directories, another approach is

    for /f "delims=" %%a in ('dir /s /b /ad "dirname" ') do if /i "%%~nxa"=="sub1" echo %%a
    

    Which in this case should be

    for /f "delims=" %%a in ('dir /s /b /ad "C:\Users\Administrator\AppData\Roaming\base\command" ') do if /i "%%~nxa"=="sub1" echo %%a
    

    The dir command produces a list in /b basic (name-only) form, /s including subdirectories, /ad of directories only (names with the directory attribute set). This list is processed line-by-line by for /f without delimiters so the entire line (including spaces, if any) is assigned to %%a and displayed.