简体   繁体   English

Windows批处理:解析路径/文件名,测试文件还是目录?

[英]Windows batch: parse path/filename, testing for file vs. directory?

Thanks to other posts here, I know how to make a batch file parse a dropped file into a path and a filename, like this: 感谢这里的其他帖子,我知道如何制作批处理文件,将拖放的文件解析为路径和文件名,如下所示:

@echo off
setlocal EnableDelayedExpansion
FOR %%a IN (%*) DO (
    if exist %%a (
        set DRVPATH="%%~dpa"
        set FILEEXT="%%~nxa"
    )
)
echo DRVPATH: %DRVPATH%
echo FILEEXT: %FILEEXT%

This works perfectly if I drop a file on the batch file. 如果我将文件拖放到批处理文件上,这将非常有效。 But if I drop a directory onto it, then it interprets the name of the directory as the filename (my %FILEEXT% variable). 但是,如果将目录放到该目录上,则它将目录的名称解释为文件名(我的%FILEEXT%变量)。

Is it possible to make the batch file test whether %FILEEXT% is actually a directory? 是否可以使批处理文件测试%FILEEXT%是否实际上是目录? If I drop a directory on the batch file, I want the %DRVPATH% variable to contain the full path including the directory name, and I want the %FILEEXT% variable to be empty. 如果将目录放在批处理文件上,则希望%DRVPATH%变量包含包含目录名称的完整路径,并且希望%FILEEXT%变量为空。

Any help in sorting this out will be gratefully received. 如有任何帮助,我们将不胜感激。

Try like this: 尝试这样:

@echo off
FOR %%a IN (%*) DO (
    if exist %%a\ (
        set DRVPATH="%%~fa"
        set FILEEXT=NIL
    ) else (
        if exist %%a (
            set DRVPATH="%%~pa"
            set FILEEXT="%%~nxa"
        )
    )
)

echo DRVPATH: %DRVPATH%
echo FILEEXT: %FILEEXT%
pause

If a directory with the name you drop exist then the var %FILEEXT% is set to NIL . 如果存在您要删除的名称的目录,则将var %FILEEXT%设置为NIL

@Echo off
pushd %1 >nul 2>&1  
If errorlevel 0 if not errorlevel 1 Echo %~nx1 is a folder
If errorlevel 1 Echo %~nx1 is not a folder
Popd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM