【问题标题】:Batch: move files group without set source/target folder批处理:移动文件组而不设置源/目标文件夹
【发布时间】:2021-02-01 16:05:09
【问题描述】:

我使用这个脚本在脚本生成的文件夹中移动一组文件

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=C:\Users\Administrator\Desktop\khin\test"
SET "destdir=C:\Users\Administrator\Desktop\khin\test"
SET /a destcount=0
SET /a maxcount=10
SET /a filecount=maxcount
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\*" '
 ) DO (
 SET /a filecount +=1
 IF !filecount! geq %maxcount% (
  SET /a filecount=0
  SET /a destcount +=1
  MD "%destdir%\folder!destcount!"
 )
 MOVE "%sourcedir%\%%a" "%destdir%\folder!destcount!\"
)
 
GOTO :EOF

我的问题是什么? 我总是需要设置一个源文件夹和一个目标文件夹

SET "sourcedir=C:\Users\Administrator\Desktop\khin\test"
SET "destdir=C:\Users\Administrator\Desktop\khin\test"

我想要什么?
我只想按批处理 .bat(在我的文件夹中),其中文件准备好在没有设置源/​​目标的情况下移动,因为我还必须对其他文件夹中的其他文件重复此操作。

示例

我有 31 个文件(示例)。我执行这个脚本,脚本创建了 3 个文件夹。对于每个文件夹,您会找到 10 个文件(除了在第四个文件夹中您会找到 1 个文件)。 为此,我的脚本需要有源和目标来移动文件。但我希望该脚本在它所在的文件夹中生成这些文件夹。

【问题讨论】:

  • 所以脚本应该(正确地)猜测文件在哪里以及您希望它们在哪里?请澄清。
  • 我不确定您是说批处理文件将存在于源文件夹中,还是您说要选择一个文件夹并根据您选择的文件夹执行批处理文件。如果您需要知道脚本路径,那就是%~dp0。如果要将文件夹拖放到批处理文件中,请使用命令行参数%1
  • @Stephan 脚本位于准备移动的文件所在的同一文件夹中。一般来说,这个脚本你可以从任何位置使用它,但我之前在源文件夹中复制了它,所以我不需要设置源/目标文件夹
  • %~dp0 引用了批处理脚本所在的文件夹。
  • SET "sourcedir=%~dp0"

标签: windows batch-file cmd


【解决方案1】:

如果您可以在 PowerShell 中执行此操作,则可能是这样的。请注意,这不会移动 .ps1 脚本文件。

$MaxCount = 10
$FileList = Get-ChildItem -File -Path $(Split-Path -Path $PSCommandPath -Parent) |
    Where-Object { $_.Name -ne $(Split-Path -Path $PSCommandPath -Leaf) }

for ($i = 0; $i -lt $FileList.Count; $i++) {
    $DirNum = [Math]::Floor($i / $MaxCount)
    $DirName = Join-Path -Path $(Split-Path -Path $PSCommandPath -Parent) `
        -ChildPath $("Dir" + $DirNum)
    if (-not (Test-Path $DirName)) { mkdir $DirName -WhatIf }
    Move-Item -Path $Filelist[$i].FullName -Destination $DirName -WhatIf
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2016-10-23
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    相关资源
    最近更新 更多