首页 > 解决方案 > 移动基于今天日期创建的文件 - powershell

问题描述

我正在尝试创建一个执行以下操作的 powershell 脚本:

将最新的 3 个子文件夹(带有文件的 abc)移动到具有今天日期的新文件夹中,而不移动旧文件

安全性具有今天生成的 3 个子文件夹以及前几天的子文件夹。

$localpath ="D:\Security\"

Get-ChildItem $localpath -Recurse | foreach {
$DateofFile = $_.LastWriteTime.ToShortDateString()
$Todaysfolder = Get-Date $DateofFile -Format yyyMMdd
$targetpath =  $Todaysfolder

Create directory if it doesn't exsist
if (!(Test-Path $targetpath))
{
 New-Item $targetpath  -type directory
}

 Get-ChildItem  $localpath | Move-Item -Destination $targetpath

}

现在的过程是抓取所有文件——即使是今天没有创建的文件,并将它们分组到一个文件夹中。该脚本将在一天结束时运行,将这 3 个子文件夹 (ABC) 移动到今天的文件夹“20200520”示例中

标签: powershell

解决方案


移动整个文件夹时无需递归 Get-ChildItem - 节省您循环浏览包含的文件。

$FromPath ="C:\fromtest"
$ToPath = "C:\totest\"+(Get-Date -Format yyyMMdd)

$FoldersToMove = Get-ChildItem $FromPath | 
    Where-Object{$_.LastWriteTime -ge (Get-Date).date}

#Create directory if it doesn't exsist
if (!(Test-Path $ToPath)){
    New-Item $ToPath -type directory
}

foreach ($Folder in $FoldersToMove){
    $Folder | Move-Item -Destination $ToPath
}

推荐阅读