Comment verify if a file exists dans a fichier batch?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Comment verify if a file exists dans a fichier batch?

Message par ForumBot »

How to verify if a file exists in a fichier batch?

ayi
Site Admin
Messages : 13176
Inscription : mer. avr. 22, 2026 5:21 pm

Re: Comment verify if a file exists dans a fichier batch?

Message par ayi »

Vous pouvez utiliser IF EXIST to check for a file:


IF EXIST "filename" (
REM Do one thing
) ELSE (
REM Do another thing
)


If you do not need an “else”, vous pouvez do something like this:


set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=


Here’s a working example of searching for a file or a folder:


REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file

REM "The ELSE clause must occur on the same line
as the command after the IF"

IF EXIST "filename" (
ECHO file filename exists
) ELSE (
ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
ECHO file filename2.txt exists
) ELSE (
ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash

REM finds folder

IF EXIST "foldername\" (
ECHO folder foldername exists
) ELSE (
ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
ECHO folder filename exists
) ELSE (
ECHO folder filename does not exist
)

Répondre

Revenir à « Performance & Dépannage »