【问题标题】:PowerShell move most recent file from each folderPowerShell 从每个文件夹中移动最新文件
【发布时间】:2017-10-04 15:32:52
【问题描述】:

我需要一些有关 powershell 的帮助 - 我想在特定文件夹的所有子文件夹中进行搜索,并在每天上午 9 点将每个子文件夹中的最新文件复制到一个新文件夹中。因此,我想在文件夹 A 的子文件夹 a、b 和 c 中搜索以分别在 a、b 和 c 中选择最新的文件,并将所有三个文件移动到文件夹 B 之外(单个文件夹)。我是 PowerShell 的新手 - 感谢任何帮助。我基本上尝试过使用它,但它会创建一个备份:Copy most recent file from folder to destination

Clear-Host
$ChildFolders = @('In_a', 'In_b', 'In_c')

for($i = 0; $i -lt $ChildFolders.Count; $i++){

$FolderPath = "C:\FolderA\" + $ChildFolders[$i]
$DestinationPath = "C:\FolderB\" [$i]

gci -Path $FolderPath -File | Sort-Object -Property LastWriteTime -Descending | Select FullName -First 1 | %($_){ 
$_.FullName
Copy-Item $_.FullName -Destination $DestinationPath 
}

【问题讨论】:

  • 是否有任何文件具有相同的名称?因为它可能会覆盖另一个文件
  • 不,都是单独命名的

标签: powershell


【解决方案1】:

获取子文件夹

获取子文件夹中的所有文件

按创建日期将文件排序到数组中

获取第一个条目

将文件移动到目标目录

*它会覆盖目标文件夹中的同名文件

Function Get-LatestFiles($SourceFolder,$Destination){
    $Subfolders = Get-ChildItem $SourceFolder -Directory
    [System.Collections.ArrayList]$SubFoldersExpanded = new-object System.Collections.ArrayList
    Foreach($SubFolder in $SubFolders){
        $SubFolderExpanded =  $Subfolder | %{(Get-ChildItem $_.FullName -File -Depth 1 | Sort-Object -Property CreationTime -Descending)}
        if($SubFolderExpanded.Count -gt 0){
            $SubFolderExpanded[0] | %{Move-Item $_.FullName -Destination $Destination -force}
        }
    }
}
Get-LatestFiles -SourceFolder C:\test -Destination C:\test01

【讨论】:

  • 谢谢 - 只是想弄清楚这个的逻辑。是否也可以在特定时间运行命令?例如。上午 9 点?
  • 你需要一些东西来启动它,比如计划任务。如果此解决方案有效,请确保对其进行投票
猜你喜欢
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多