- 1 year ago
Batch> Dir command craps out when denied access to a folder/file, would like it to just SKIP it, or an alternative
In Windows batch scripting, the dir
command can terminate with an error if it encounters a folder or file that you do not have access to. To make it skip inaccessible folders and files instead of terminating, you can redirect the error output to the null device using 2>nul
.
Here's an example of how you can modify the dir
command to skip inaccessible items:
batchdir /b /s /a-d "C:\Path\to\folder" 2>nul
In this example:
/b
specifies that you want to display only the bare format (file names only)./s
tellsdir
to include subdirectories recursively./a-d
excludes directories from the listing."C:\Path\to\folder"
is the path to the folder you want to list.
By appending 2>nul
to the command, any error output (denied access messages) will be redirected to the null device, effectively suppressing them and allowing the dir
command to continue executing.
Alternatively, you can use the FOR
command with the /R
option to iterate over files in a directory tree. This approach also allows you to skip inaccessible items:
batchfor /r "C:\Path\to\folder" %%F in (*) do (
echo %%F
)
Replace "C:\Path\to\folder"
with the actual path to your target folder. The FOR /R
loop iterates over all files in the directory tree and executes the command inside the parentheses for each file. In this example, it simply echoes the file path, but you can replace echo %%F
with any other desired command or action.
By using either of these approaches, you can make the batch script skip inaccessible folders and files while continuing the execution of the dir
command or file iteration.