파일이 배치 스크립트의 디렉토리인지 테스트하는 방법은 무엇입니까?
-
02-07-2019 - |
문제
파일이 디렉토리인지 확인하는 방법이 있습니까?
변수에 파일 이름이 있습니다. Perl에서 나는 이것을 할 수있다 :
if(-d $var) { print "it's a directory\n" }
해결책
당신은 그렇게 할 수 있습니다 :
IF EXIST %VAR%\NUL ECHO It's a directory
그러나 이것은 이름에 공간이없는 디렉토리에만 적용됩니다. 변수 주변에 따옴표를 추가하여 공간을 처리하면 작동이 중지됩니다. 공백으로 디렉토리를 처리하려면 파일 이름을 다음과 같이 짧은 8.3 형식으로 변환하십시오.
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
그만큼 %%~si
변환 %%i
8.3 파일 이름으로. 당신이 수행 할 수있는 다른 모든 트릭을 보려면 FOR
변수가 입력됩니다 HELP FOR
명령 프롬프트에서.
(참고 - 위에 주어진 예제는 배치 파일로 작동하는 형식입니다. 명령 줄에서 작동하려면 %%
~와 함께 %
두 곳 모두에서.)
다른 팁
이것은 작동합니다 :
if exist %1\* echo Directory
공백이 포함 된 디렉토리 이름으로 작동합니다.
C:\>if exist "c:\Program Files\*" echo Directory
Directory
디렉토리에 공간이 포함 된 경우 인용문이 필요합니다.
C:\>if exist c:\Program Files\* echo Directory
다음과 같이 표현할 수 있습니다.
C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory
이것은 집에서 시도하기에 안전합니다, 아이들!
최근 위의 접근 방식으로 실패했습니다. 그들이 과거에 일했고, 아마도 DFS와 관련이있을 것입니다. 이제 사용 파일 속성 첫 번째 숯을 자릅니다
@echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF
이전 제품에 이르기까지 이것이 효과가 있습니다.
if exist %1\ echo Directory
발신자가 공급하기 때문에 약 %1의 인용문이 필요하지 않습니다. 이것은 1 년 전의 답변에 대한 전체 키 스트로크를 절약합니다. ;-)
다음은 자격을 갖춘 경로를 구축하는 데 사용하는 스크립트가 있습니다. 그런 다음 경로가 디렉토리인지 테스트하기 위해 푸시합니다. 네트워크 경로뿐만 아니라 공간이있는 경로에 어떻게 작동하는지 확인하십시오.
@echo off
if [%1]==[] goto usage
for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir
:notdir
echo not a directory
goto exit
:isdir
popd
echo is a directory
goto exit
:usage
echo Usage: %0 DIRECTORY_TO_TEST
:exit
위의 내용을 "isdir.bat"로 저장 한 샘플 출력 :
C:\>isdir c:\Windows\system32
is a directory
C:\>isdir c:\Windows\system32\wow32.dll
not a directory
C:\>isdir c:\notadir
not a directory
C:\>isdir "C:\Documents and Settings"
is a directory
C:\>isdir \
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory
이것은 완벽하게 작동합니다
if exist "%~1\" echo Directory
%1에서 따옴표를 제거하려면 %~ 1을 사용하고 끝에 백 슬래시를 추가해야합니다. 그런 다음 THW 전체를 다시 Qutes에 넣으십시오.
NUL 기술은 8.3 호환 파일 이름에서만 작동하는 것 같습니다.
(즉,`d : documents and settings`는 "나쁜"이고`d : docume ~ 1이 "좋은"입니다)))))
디렉토리 이름에 "문서 및 설정"과 같은 공백이있을 때 "Nul"Tecnique를 사용하는 데 어려움이 있다고 생각합니다.
Windows XP Service Pack 2를 사용하고 있으며 %SystemRoot % System32 CMD.Exe에서 CMD 프롬프트를 시작합니다.
다음은 작동하지 않은 것과 저에게 효과가있는 것의 예입니다.
(이것은 대화식 프롬프트에서 "라이브"가 수행 된 시연입니다. 스크립트로 디버깅을 시도하기 전에 그 일을해야한다고 생각합니다.)
이것은 작동하지 않았습니다.
D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes
이것은 작동하지 않았습니다.
D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes
이것은 작동합니다 (나를 위해) :
D:\Documents and Settings>cd ..
D:\>REM get the short 8.3 name for the file
D:\>dir /x
Volume in drive D has no label.
Volume Serial Number is 34BE-F9C9
Directory of D:\
09/25/2008 05:09 PM <DIR> 2008
09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25
09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe
02/14/2008 12:32 PM <DIR> cygwin
[여기 봐 !!!! ]]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings
09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads
10/12/2007 11:25 AM <DIR> NVIDIA
05/13/2008 09:42 AM <DIR> Office10
09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM <DIR> TEMP
02/14/2008 12:26 PM <DIR> tmp
01/21/2008 07:05 PM <DIR> VXIPNP
09/23/2008 12:15 PM <DIR> WINDOWS
02/21/2008 03:49 PM <DIR> wx28
02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free
D:\>REM now use the \NUL test with the 8.3 name
D:\>if exist d:\docume~1\NUL echo yes
yes
이것은 작동하지만 Dot은 이미 디렉토리에 있다는 것을 의미하기 때문에 어리석은 일입니다.
D:\Documents and Settings>if exist .\NUL echo yes
이것은 작동하고 공백이있는 경로를 처리합니다.
dir "%DIR%" > NUL 2>&1
if not errorlevel 1 (
echo Directory exists.
) else (
echo Directory does not exist.
)
아마도 내 의견으로는 다른 솔루션보다 가장 효율적이지만 읽기가 쉽지 않을 것입니다.
@batchman61의 접근 방식의 변형 (디렉토리 속성 확인).
이번에는 외부 '찾기'명령을 사용합니다.
(아, 그리고 참고 &&
장난. 이것은 긴 지루한 것을 피하기위한 것입니다 IF ERRORLEVEL
통사론.)
@ECHO OFF
SETLOCAL EnableExtentions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
ECHO %1 is a directory
)
출력 예 On :
- 디렉토리.
- 디렉토리 기호 링크 또는 접합.
- 고장난 디렉토리 기호 링크 또는 접합. (링크를 해결하려고하지 않습니다.)
- 읽기 권한이없는 디렉토리 (예 : "C : 시스템 볼륨 정보")
나는 이것을 사용한다 :
if not [%1] == [] (
pushd %~dpn1 2> nul
if errorlevel == 1 pushd %~dp1
)
매우 간단한 방법은 아이가 존재하는지 확인하는 것입니다.
자녀가 자녀가없는 경우 exist
명령은 false를 반환합니다.
IF EXIST %1\. (
echo %1 is a folder
) else (
echo %1 is a file
)
충분한 액세스 권한이 없으면 허위 부정적인가있을 수 있습니다 (테스트하지 않았습니다).
기반 이 기사 제목은 "디렉토리의 배치 파일 테스트는 어떻게"완전히 신뢰할 수 없다 "라는 제목의 제목.
하지만 방금 테스트했습니다.
@echo off
IF EXIST %1\NUL goto print
ECHO not dir
pause
exit
:print
ECHO It's a directory
pause
그리고 그것은 작동하는 것 같습니다
내 솔루션은 다음과 같습니다.
REM make sure ERRORLEVEL is 0
TYPE NUL
REM try to PUSHD into the path (store current dir and switch to another one)
PUSHD "insert path here..." >NUL 2>&1
REM if ERRORLEVEL is still 0, it's most definitely a directory
IF %ERRORLEVEL% EQU 0 command...
REM if needed/wanted, go back to previous directory
POPD
가능하다면 cd
그것에 디렉토리입니다.
set cwd=%cd%
cd /D "%1" 2> nul
@IF %errorlevel%==0 GOTO end
cd /D "%~dp1"
@echo This is a file.
@goto end2
:end
@echo This is a directory
:end2
@REM restore prior directory
@cd %cwd%
이 주제에 대한 내 기능 스크립트를 게시하고 싶습니다. 언젠가 누군가에게 유용하기를 바랍니다.
@pushd %~dp1
@if not exist "%~nx1" (
popd
exit /b 0
) else (
if exist "%~nx1\*" (
popd
exit /b 1
) else (
popd
exit /b 3
)
)
이 배치 스크립트는 파일/폴더가 존재하는지 확인하고 파일 또는 폴더인지 확인합니다.
용법:
Script.bat "Path"
종료 코드 :
0 : 파일/폴더가 존재하지 않습니다.
1 : 존재하며 폴더입니다.
3 : 존재하며 파일입니다.
CD
반환합니다 EXIT_FAILURE
지정된 디렉토리가 존재하지 않는 경우 그리고 당신은 얻었습니다 조건부 처리 기호, 당신은 이것에 대해 아래를 좋아할 수 있습니다.
SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error
:Error
CD %cd_backup%
Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:
@echo off if exist c:\temp\data.csv echo data.csv is a file if exist c:\temp\data.csv\ echo data.csv is a directory if exist c:\temp\data.csv\nul echo data.csv is a directory if exist k:\temp\nonexistent.txt echo nonexistent.txt is a file if exist k:\temp\something.txt echo something.txt is a file if exist k:\temp\something.txt\ echo something.txt is a directory if exist k:\temp\something.txt\nul echo something.txt is a directory
produces:
data.csv is a file something.txt is a file something.txt is a directory something.txt is a directory
So beware if your script might be fed a mapped or UNC path. The pushd solution below seems to be the most foolproof.
This is the code that I use in my BATCH files
```
@echo off
set param=%~1
set tempfile=__temp__.txt
dir /b/ad > %tempfile%
set isfolder=false
for /f "delims=" %%i in (temp.txt) do if /i "%%i"=="%param%" set isfolder=true
del %tempfile%
echo %isfolder%
if %isfolder%==true echo %param% is a directory
```
Ok... the 'nul' trick doesn't work if you use quotes in names, which accounts for most files with long file names or spaces.
For example,
if exist "C:\nul" echo Directory
does nothing, but
if exist C:\nul echo Directory
works.
I finally came up with this, which seemed to work for all cases:
for /f %%i in ('DIR /A:D /B %~dp1 ^| findstr /X /c:"%~nx1"') do echo Directory
or if you can assure you meet all of the requirements for 'nul' a solution is:
if exist %~sf1\nul echo Directory
Put these into a batch file like 'test.bat' and do 'test.bat MyFile'.
Here is my solution after many tests with if exist, pushd, dir /AD, etc...
@echo off
cd /d C:\
for /f "delims=" %%I in ('dir /a /ogn /b') do (
call :isdir "%%I"
if errorlevel 1 (echo F: %%~fI) else echo D: %%~fI
)
cmd/k
:isdir
echo.%~a1 | findstr /b "d" >nul
exit /b %errorlevel%
:: Errorlevel
:: 0 = folder
:: 1 = file or item not found
- It works with files that have no extension
- It works with folders named folder.ext
- It works with UNC path
- It works with double-quoted full path or with just the dirname or filename only.
- It works even if you don't have read permissions
- It works with Directory Links (Junctions).
- It works with files whose path contains a Directory Link.
One issue with using %%~si\NUL
method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si
resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.
An alternative method:
dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)
:IsFile
echo %F% is a file
goto done
:IsDir
echo %F% is a directory
goto done
:done
You can replace (goto IsFile)||(goto IsDir)
with other batch commands:
(echo Is a File)||(echo is a Directory)
Can't we just test with this :
IF [%~x1] == [] ECHO Directory
It seems to work for me.