-1

I would like to move all .txt files present in a source directory (including .txt present in subfolders) to a destination directory.

For eg: Source directory: D:\OFFICE work\robtest\test1

Above directory also contains many subfolders.

Destination directory: D:\OFFICE work\robtest\test2

I would like to move only .txt files in source dir to the above mentioned destination directory, in such a way that only 3 .txt files must be present per sub folder (includes random folder creation) in the destination directory.

Below is the code I tried, but PowerShell says

The filename, directory name, or volume label syntax .(D:\OFFICE work\robtest\test1\testtest\testtest2\ New folder\test01112.txt\ ) is incorrect.

I am not sure why there is extra '/' after the above path in 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;
    }
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    Is there a special reason to use robocopy? Why not use Move-Item? Also, at which line does the error occur? – TToni Dec 16 '17 at 16:34

2 Answers2

1

You're getting the error (and the "directory" in the output) because robocopy expects two folders as the first and second argument, optionally followed by a list of filename specs, but you're providing the path to a file as the source.

From the documentation (emphasis mine):

Syntax

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

Parameters

  • <Source> Specifies the path to the source directory.
  • <Destination> Specifies the path to the destination directory.
  • <File> Specifies the file or files to be copied. You can use wildcard characters (* or ?), if you want. If the File parameter is not specified, *.* is used as the default value.
  • <Options> Specifies options to be used with the robocopy command.

Since you're moving one file at a time and apparently don't want to maintain the directory structure I'd say robocopy isn't the right tool for what you're doing anyway.

Replace

robocopy $file.FullName $destiny /mov

with

Move-Item $file.FullName $destiny

and the code should do what you want.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

robocopy $file.Directory $destiny $file /mov

solved this issue.