Search code examples
powershellnetwork-drive

Move amount of folders recursive to another folder in the same folder with PowerShell


I have a root folder (a mapped network drive) to Z, in this folder I have a folder named Archive and I would like to move some folders in Z to archive folder.

The titles of folders to move I have in a csv file.

I've created a PowerShell script, but somehow it does not really work, it does move one folder, but then nothing happens even in the PowerShell command, just empty and after a while nothing happens and I have to close the PowerShell window.

So if I have ten folders to copy only the first is moved and that is it.

Here is the code:

$currentPath = Split-Path -Parent $PSCommandPath;
$areaCsvPath = $currentPath + "\CSVFile.csv";
write-host $areaCsvPath;

$csv = Import-Csv $areaCsvPath;
$count =0;

$Creds = Get-Credential

foreach ($row in $csv)
{
    Get-ChildItem -Path "Z:\" -Recurse |
      Where-Object {$_.name -eq $row.Title} |
      Move-Item -destination "Z:\_Archive" -Credential $Creds

    $count++;
    write-host $count;

}

CSV is as follows

Title
12345
22223
75687
...

Solution

  • I don't see why only one folder gets moved but you could try the following script which should be much faster because the Get-ChildItem cmdlet is only called once:

    $currentPath = Split-Path -Parent $PSCommandPath;
    $areaCsvPath = $currentPath + "\CSVFile.csv";
    write-host $areaCsvPath;
    
    $csv = Import-Csv $areaCsvPath;
    $Creds = Get-Credential
    
    Get-ChildItem -Path "Z:\" -Recurse |
          Where-Object Name -in ($csv | select -expand Title) |
          Move-Item -destination "Z:\_Archive" -Credential $Creds
    

    If the folders are at the top level on Z: you should omit the -Recurse parameter. Also if you only want to move folders, you could add the -Directory switch to the Get-ChildItem invoke to further improve the performance.