Reputation: 136
Using Powershell to search (Get-ChildItem) for specific files that you need to copy to a new location with the same folder structure seemed to be not trivial with Powershell. Combining Get-ChildItem with Copy-Item usually gets you all the files that meet your criteria but in a single folder at the destination rather than following the same folder structure at the destination. If that is what you want, then perfect. But if you want to have the files saved using the same source folder structure at the destination then I have some sample code that will work. Note I intentionally did not try to make this a one-line program. I wanted to breakout the various pieces and document their purpose, so you have useful code down the road to use for other/similar purposes.
My requirement was I needed to move all files less than 3 hours old (either new or modified within the last 3 hours) from a network share to a local drive (D:). But I needed the folder structure to be intact. I'm sure many of you are screaming use RoboCopy. I have used it for many things and it does a great job. I wanted something within PowerShell and I was having problems getting as granular (3 hour limit) as I needed.
Upvotes: 0
Views: 878
Reputation: 136
Here is the PowerShell code I used to solve this requirement:
$SourceBase = "G:\" # the part of the source name that does not factor into how to save it to the new location
$DestBase = "D:\SGdata\" # the part of the destination name that does not change as you create the path to the file loc
$SrcSPfolder = "G:\SAP Reports" # Top folder to begin search
# Grab a list of valid files that meet the Where-Object test of 3 hours
$filelist = Get-ChildItem -Path $SrcSPfolder -Recurse -File |
Where-Object -filterScript {!($_.PSIsContainer) -and ($_.LastWriteTime -gt [datetime]::now.AddMinutes(-180)) }
" file count = " + $filelist.Count
# Now for each of those source files convert the path name to the dest format and create the folder structure and
# then save the file in the new location
foreach ($fs in $filelist) {
$TheSourceFullName = $fs.fullname
$TheDestFullName = $TheSourceFullName.Replace($SourceBase , $DestBase )
# Grab the destination path
$path = split-path $TheDestFullName
# Create destination folder structure
New-Item -Path $path -Type directory -force | Out-Null
# Copy source file to destination with new structure
copy-item -Path $TheSourceFullName -Destination $TheDestFullName
}
Upvotes: 0