Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Path 批处理:从绝对路径获取最后一个文件夹名称_Path_Batch File_Directory_Absolute - Fatal编程技术网

Path 批处理:从绝对路径获取最后一个文件夹名称

Path 批处理:从绝对路径获取最后一个文件夹名称,path,batch-file,directory,absolute,Path,Batch File,Directory,Absolute,我正在使用批处理脚本将文件自动备份到我的NAS,我需要从绝对路径获取最后一个文件夹名,例如从“C:\Things\folder”到“folder”这有点麻烦,但您可以使用: Set NasPath=C:\Things\Folder Set NasFolder=%NasPath% :GetFolder Set GetFolderTemp=%NasFolder:*\=% If Not %GetFolderTemp%==%NasFolder% ( Set NasFolder=%GetFolde

我正在使用批处理脚本将文件自动备份到我的NAS,我需要从绝对路径获取最后一个文件夹名,例如从“C:\Things\folder”到“folder”

这有点麻烦,但您可以使用:

Set NasPath=C:\Things\Folder
Set NasFolder=%NasPath%
:GetFolder
Set GetFolderTemp=%NasFolder:*\=%
If Not %GetFolderTemp%==%NasFolder% (
    Set NasFolder=%GetFolderTemp%
    Goto :GetFolder
)
Echo NasPath  =%NasPath%
Echo NasFolder=%NasFolder%
Exit /B
无论您做什么,都不要在
setnaspath=…
语句的任何部分加引号。使用引号的方式如下:

Set FromPath=C:\Program Files\Blah
Set NasPath=C:\Things\Folder
RoboCopy "%FromPath%" "%NasPath%"
Set FromPath="C:\Program Files\Blah"
Set NasPath="C:\Things\Folder"
RoboCopy %FromPath% %NasPath%
不要以这种方式使用引号:

Set FromPath=C:\Program Files\Blah
Set NasPath=C:\Things\Folder
RoboCopy "%FromPath%" "%NasPath%"
Set FromPath="C:\Program Files\Blah"
Set NasPath="C:\Things\Folder"
RoboCopy %FromPath% %NasPath%

假设
C:\Program Files\Mickey\Mouse
类似路径(不带引号),也可以使用以下代码:

setlocal EnableDelayedExpansion

set path=C:\Program Files\Microsoft\Mickey\Mouse
:shift
for /f "tokens=1* delims=\/" %%i in ( "!path!" ) do (
    set folder=%%i
    set path=%%j
)
if not [!path!] == [] goto :shift

echo folder: !folder!

endlocal

为了避免空间问题,我建议使用以下代码:

Set NasPath=C:\Things\My Space\Folder
Set GetFolderTemp=%NasPath%
:GetFolder
FOR /F "tokens=1,* delims=\" %%1 IN ("%GetFolderTemp%") do (
set NasFolder=%%1
set GetFolderTemp=%%2
)
if not "a%GetFolderTemp%"=="a" goto :GetFolder

echo %NasFolder%

+1,但您应该始终以这种方式使用引号
Set“FromPath=C:\Program Files\Blah”
否则您将失败,因为
Set FromPath=C:\Documents&Settings
@jeb
Set FromPath=C:\Docs and Settings
是有效的。正如@Hand-E所说,要使用该变量,请将其括在引号中,
“%FromPath%”
。很明显,
文档和设置
可以工作,但如果使用了符号,则会失败,并且在文件/pathname中允许使用符号和。请注意,这将覆盖
路径
环境变量。