I have a scenario where I need to search folders and sub folders for certain file types. if those types are found then the whole root folder with all files and sub folders needs to be moved.
Source c:\testsource example: search for *.exe files the following file is found c:\testsource\folder1\subfolder1\testfile.exe then folder1 with all files and subfolders needs to be moved to c:\testdestination
I first tried this with a batch file and was able to move all files in subfolder1 but not any of the other files or directory structure. I then started working on it in powershell but had similar results. I think what I need is to search, and if found capture the folder path, then move the folder, but not sure how to do that.
Batch file I created:
for /r "C:\TestSource" %i in (*.exe)do move "%~dpi\*" "C:\TestDestination\"
Powershell Script
$Source = "C:\testsource"
$Dest = "C:\testdestination"
Get-ChildItem -Recurse -Path $Source | Where {$_.fullname -Match '.*\.exe'} | Move-Item -Destination $Dest
Any help here would be much appreciated
CodePudding user response:
You will need a loop to check for each direct subfolder of the source folder if it has the desired file in one of its subfolders. ... something like this:
$Source = 'C:\testsource'
$Dest = 'C:\testdestination'
Get-ChildItem -Path $Source -Directory |
ForEach-Object{
If (Get-ChildItem -Path $_.FullName -Recurse -File -Filter '*.exe'){
Move-Item -Path $_.FullName -Destination $Dest -Recurse
}
}