使用 Powershell 搜索 (Get-ChildItem) 以查找需要复制到具有相同文件夹结构的新位置的特定文件对于 Powershell 来说似乎并不简单。将 Get-ChildItem 与 Copy-Item 结合使用通常可以让您获得所有符合条件的文件,但位于目标位置的单个文件夹中,而不是遵循目标位置的相同文件夹结构。如果那是你想要的,那就完美了。但是,如果您想在目标位置使用相同的源文件夹结构保存文件,那么我有一些示例代码可以使用。请注意,我有意没有尝试将它变成一个单行程序。我想分解各个部分并记录它们的用途,这样你就有了有用的代码用于其他/类似的目的。
我的要求是我需要将所有不到 3 小时的文件(新文件或最近 3 小时内修改过的文件)从网络共享移动到本地驱动器 (D:)。但我需要文件夹结构完好无损。我敢肯定你们中的许多人都在尖叫使用 RoboCopy。我用它做了很多事情,它做得很好。我想要 PowerShell 中的一些东西,但我在获得所需的粒度(3 小时限制)时遇到了问题。
这里是我用来解决这个需求的PowerShell代码:
$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
}