compperson
compperson

Reputation: 13

Batch file to create subfolder in other subfolders, but only at top level

I have a similar problem to this post, but I couldn't get the solution to work (I'm a total novice).

I have a set of folders on a network drive, each folder named after a manager (e.g. \sfnetfile\DEPT\HR_Manager\Manager, Test and \sfnetfile\DEPT\HR_Manager\Manager, Test 2). I am trying to get a folder/subfolder combo created in each manager folder of 2013\Variable. In some cases managers already have a 2013 subfolder, but not the Variable sub-subfolder (excuse the silly terminology).

I also want to prevent the batch file from creating the 2013\Variable folder in existing other subfolders within each manager folders (so I don't want it, for example, creating another level down: \sfnetfile\DEPT\HR_Manager\Manager, Test 2\2012\2013\Variable.

Here is my code:

FOR /d %A IN (\sfnetfile\DEPT\HR_Manager*) DO mkdir "%A"\2013\Variable

Upvotes: 0

Views: 3921

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

Something like this should do:

@echo off

for /d %%d in (\\sfnetfile\DEPT\HR_Manager\*) do md "%%~d\2013\Variable" 2>nul

assuming that sfnetfile is the name of a remote server and DEPT is a shared folder on that server. If sfnetfile is a top level folder on a mapped network drive, change that to:

@echo off

for /d %%d in (X:\sfnetfile\DEPT\HR_Manager\*) do md "%%~d\2013\Variable" 2>nul

where X: is the drive letter of the network drive.

Edit: As @dbenham correctly mentions, redirecting error output (to suppress error messages for existing leaf folders) will also suppress any other error message. A more sophisticated approach would check if the folder doesn't already exist and only then create it:

@echo off

setlocal EnableDelayedExpansion

for /d %%d in (\\sfnetfile\DEPT\HR_Manager\*) do (
  set "folder=%%~d\2013\Variable"
  if exist "!folder!" (
    if not exist "!folder!\" echo "!folder!" exists as a file! 1>&2
  ) else (
    mkdir "!folder!"
  )
)

Upvotes: 1

Related Questions