如何根据文件名自动创建文件夹并使用 .BAT 将文件移动到其文件夹中

问题描述 投票:0回答:1

我已经解决了我的问题...我还没有解决的是,如果

.bat
文件位于父文件夹中并且它应该适用于所有子文件夹,该怎么做?

目前存在一个限制,即仅当

.bat
文件与文件位于同一文件夹中时才会创建文件夹。如果文件位于子文件夹内,则无法创建文件夹。

我拥有的是:

这个

.bat
的文件名是:

组织.bat

@echo off
for %%i in (*) do (
 if not "%%~ni" == "organize" (
  md "%%~ni" && move "%%~i" "%%~ni"
 )
)

我现在是怎么做的:

  1. 我将
    .bat
    文件与文件一起放在一个文件夹中
  2. 当我单击它时,它将创建一个基于该文件夹内的文件名称的文件夹
  3. 它还将移动同名文件夹中的每个文件

我需要什么:

  1. .bat
    文件放在主文件夹中,其中包含许多子文件夹
  2. 单击它即可执行与上述相同的任务

如果我的解释令人困惑,请道歉...我希望它仍然可以理解。

提前谢谢您!

windows batch-file cmd directory
1个回答
1
投票

您的尝试非常接近工作,但请注意使用简单方法而不检查每个细节的问题,因此,从这里开始:-

@echo off & Title %~n0
REM I recommend using cd /d "%~dp0" to ensure you start from the known cmd file folder location not some system folder
cd /D "%~dp0"

REM clear the second-pass file from any previous run
del second-pass.bat

REM add the /R switch to run through subdirs
for /R %%i in (*) do (

REM This is a relatively simple slow approach. So there will be repeats for make dir and
REM not all files will always need a move, so you should check the contents prior to run the second-pass.bat

REM replace organize to %~n0 so as to aid renaming by other users
 if not "%%~DPni" == "%~DPn0" (
REM to allow for nested paths we need a fuller DP location for N (check it works exactly as desired then remove the echos)
  echo md "%%~DPni" >>second-pass.bat && echo move "%%~i" "%%~DPni" >>second-pass.bat
 )
)

注意带有双 .dot.s 的文件,例如 cmd.exe.lnk,因此请先检查这些 echo 的

md "C:\Users\me\Favorites\Links\cmd.exe"
move "C:\Users\me\Favorites\Links\cmd.exe.lnk" "C:\Users\me\Favorites\Links\cmd.exe"
© www.soinside.com 2019 - 2024. All rights reserved.