PowerShell to move all files with same keyword string "copy"

Eaven HUANG 2,191 Reputation points
2022-06-17T02:59:24.183+00:00

Dear all,

One of our users mistakenly took the wrong action which caused all the files (folder excluded) within his onedrive were copied in the same path, all the files are either started or ended with 'copy' keyword. I tried to use following script but it didn't work out for me, anything I did wrong?

$dir1 = "C:\Onedrivetesting"  
$dir2 = "C:\Des"  
  
$results = Get-ChildItem -Path $dir1 -recurse |  Select-String -Pattern 'copy'  
  
$results | ForEach-Object{  
    $parentFolder = ($_.Path -split "\\")[-2]  
    Copy-Item -Path $_.Path -Destination ([io.path]::combine($dir2,$parentFolder))  
}  
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DaveK 1,871 Reputation points
    2022-06-17T10:53:59.543+00:00

    Hi,

    I would do something with the Get-Childitem -Filter option like to get the list of files. This would get all files starting or ending with 'copy' and any file extension.

    Get-ChildItem -Path $dir1 -Recurse -Filter "*Copy*.*"  
    

    This should get you roughly where you want however you might need to edit as you've spill on \ but your example shows two local folder paths on C: so you might need to amend slightly depending on what your doing and/or if network paths are involved.

    $dir1 = "C:\Onedrivetesting"  
    $dir2 = "C:\Des"  
      
    $results = Get-ChildItem -Path $dir1 -recurse -filter '*copy*.*'  
      
    $results | ForEach-Object{  
    	$parentFolder = $_.FullName.split("\\")[-2]  
    	Copy-Item -Path $_.FullName -Destination ([io.path]::combine($dir2,$parentFolder)) -WhatIf  
    }  
    

    Also remove the -WhatIf after testing :)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.