将文件移动到每年/每月的新子文件夹中

时间:2018-01-23 16:46:56

标签: powershell

我正在尝试将每个subfolder下的所有文件移到另一个名称为subfoldername_mmm_yyyy的文件夹中。

以下代码仅将所有子文件夹中的所有文件移动到名为subfoldername_subfoldername_mmm_yyyy的一个文件夹中。

我知道我的每个循环都不正确,但我不知道如何修复它们,请有人帮忙吗?

$curr_date = Get-Date
$folder_path = "C:\Logs\"
$file_type = "C:\Logs\*.log*"
$destination = "C:\Archive\"

# delete tmp files if existed
$deletefile = Get-ChildItem $destination -recurse -include *.7z.tmp -force | remove-item

# set min age of files
$max_days = "-1"

# determine how far back we go based on current date
$zip_date = $curr_date.AddDays($max_days)

Get-ChildItem -Path $folder_path | Where-Object { $_.Attributes -eq "Directory" } | foreach {
    # obtain all subfolders
    $servername = Get-ChildItem -Path $folder_path | Where-Object { $_.Attributes -eq "Directory" }

    # move all files into servername_mmm_yyyy folder
    Get-ChildItem $file_type -Recurse | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false)}| foreach {
        $x = $_.LastWriteTime.ToShortDateString()
        $month_year = Get-Date $x -Format MMM_yyyy
        $file_destination = ($destination) + ($servername) + "_" + ($month_year)
        if (test-path $file_destination) { 
            move-item $_.fullname $file_destination 
        }
        else {
            new-item -ItemType directory -Path $file_destination
            move-item $_.fullname $file_destination 
        }
    }
}

2 个答案:

答案 0 :(得分:0)

变化: Get-ChildItem $file_type -Recurse | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false)} ...Get-ChildItem $file_type -Recurse | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false) -and $_.Name.EndsWith(".log")} 这应该只是你想要定位的文件

答案 1 :(得分:0)

我发现了我的问题。我就是这样做的。

我只需要获取每个文件的文件夹名称并构建目标路径。因此,我只需要一个foreach循环。

library(tidyverse)
iris %>% select_if(negate(is.numeric))