PowerShell中的自定义robocopy脚本

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

我想将源目录中存在的所有.txt文件(包括子文件夹中存在的.txt)移动到目标目录。

例如:源目录:D:\OFFICE work\robtest\test1

上面的目录还包含许多子文件夹。

目的地目录:D:\OFFICE work\robtest\test2

我想只将源目录中的.txt文件移动到上面提到的目标目录,这样每个子文件夹(包括随机文件夹创建)中只有3个.txt文件必须存在于目标目录中。

下面是我尝试过的代码,但PowerShell说

文件名,目录名或卷标语法。(D:\ OFFICE work \ robtest \ test1 \ testtest \ testtest2 \ New folder \ test01112.txt \)不正确。

我不确定为什么在robocopy中的上述路径之后会有额外的'/'。

$fileperfolder = 3
$source = "D:\OFFICE work\robtest\test1";
$dest = "D:\OFFICE work\robtest\test2";
$folderName = [System.IO.Path]::GetRandomFileName();
$fileList = Get-ChildItem -Path $source -Filter *.txt -Recurse
Write-Host $fileList
$i = 0;
foreach ($file in $fileList) {
    $destiny = $dest + "\" + $folderName
    Write-Host $file.FullName;
    Write-Host $destiny;
    New-Item $destiny -Type Directory -Force
    robocopy $file.FullName $destiny /mov
    $i++;
    if ($i -eq $fileperfolder) {
        $folderName = [System.IO.Path]::GetRandomFileName();
        $i = 0;
    }
}
powershell robocopy
2个回答
1
投票

你得到错误(和输出中的“目录”),因为robocopy期望两个文件夹作为第一个和第二个参数,可选地后面跟着文件名规范列表,但是你提供了一个文件的路径作为源。

来自documentation(强调我的):

句法

robocopy <Source> <Destination> [<File>[ ...]] [<Options>]

参数

  • <Source>指定源目录的路径。
  • <Destination>指定目标目录的路径。
  • <File>指定要复制的文件。如果需要,您可以使用通配符(*?)。如果未指定File参数,则使用*.*作为默认值。
  • <Options>指定与robocopy命令一起使用的选项。

既然你一次移动一个文件并且显然不想维护目录结构,我会说robocopy不是你正在做的事情的正确工具。

更换

robocopy $file.FullName $destiny /mov

Move-Item $file.FullName $destiny

并且代码应该做你想要的。


0
投票

robocopy $ file.Directory $ destiny $ file / mov

解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.