用于将X个文件从一个文件夹复制到另一个文件夹的Windows脚本

时间:2013-11-08 06:25:51

标签: windows powershell batch-file powershell-v2.0

我是脚本世界的新手,所以可能会问一些新手问题,但是经过这么多谷歌搜索后我找不到确切的代码。

我的要求是生成一个脚本,将X个文件从一个文件夹复制到另一个文件夹。这里应该在脚本中配置要复制的文件数,源文件和目标文件夹。

我尝试了Xcopy,Robocopy,但没有找到任何参数来限制要复制的文件数量。该程序将在Win7或Win2008服务器上运行。

请帮忙。

4 个答案:

答案 0 :(得分:3)

对于批处理文件标记:

@echo off

    setlocal enableextensions enabledelayedexpansion

    set "source=d:\temp\input"
    set "target=d:\temp\output"
    set num=10

    for /F "tokens=1,2 delims=:" %%f in ('dir /b /a-d "%source%\*"  ^| findstr /n "^" ') do (
        if %%f leq %num% (
            copy "%source%\%%g" "%target%" /y > nul 
        ) else goto endCopy
    )

:endCopy
    endlocal

答案 1 :(得分:2)

我必须说我同意vonPryz的观点。这看起来很奇怪。但是,在PowerShell中执行所需操作非常容易。只需抓住您想要使用的物品数量:

$sourceFolder = "D:\source"
$destinationFolder = "D:\copiedfiles"
$maxItems = 200
Get-Childitem $sourceFolder | Select-Object -First $maxItems | Copy-Item $destinationFolder

如果目标文件夹不存在,这甚至会创建它。

答案 2 :(得分:1)

与提出要求的人讨论并找出确切的过滤需求。

copy N files from location X to location Y几乎没有任何意义。通常有更明智的标准,例如copy all files that are changed after DATETIME from location X to location Y. If there are more than N files, pick only N oldest/newest.只有利益相关者才能告诉您预期的行为类型。如果没有更多信息,脚本很可能无法提供预期的功能。

在您知道确切的要求后,再做一些谷歌搜索解决方案。它不应该花费太多精力来找出如何在Powershell中完成任务。提示:将gci与适当的参数/过滤器一起使用,并将其结果存储在数组中。

答案 3 :(得分:0)

顺便说一句......上面的PowerShell会抛出关于不接受管道输入的命令的异常。您需要复制每个对象,因此正确的命令是:def replace_str(base, target, rep): m = 0 n = len(target) if base[m:n] == target: new_base = base[0:m] + rep + base[n:] return replace_str(new_base, target, rep) else: m = m + 1 n = n + 1 return replace_str(base, target, rep)

相关问题