powershell - 使用 powershell 将超过一周的文件夹中的文件存档到子文件夹
问题描述
我已经尝试在 powershell 脚本下将超过 7 天的文件从 Newfolder 移动到 Archive_folder。该脚本正在将整个路径移动到 Archive_folder (意味着它创建文件夹 \Users\529817\New 文件夹到 Archive_folder,然后复制文件而不是压缩文件夹),我需要帮助将文件从 NewFolder 复制到 Archive_folder 并压缩文件夹。
$ArchiveYear = "2018"
$ArchiveMonth = "10"
$ArchiveDay = "10"
$SourcePath = "C:\Users\529817\New folder"
$TargetPath = "C:\Users\529817\New folder\Archive_folder"
$YourDirToCompress = "C:\Users\529817\New folder"
$ZipFileResult = "C:\Users\529817\New folder\Archive_folder\$ArchiveDay$ArchiveMonth.zip"
Get-ChildItem $YourDirToCompress -Directory |
#where { $_.Name -notin $DirToExclude} |
Compress-Archive -DestinationPath $ZipFileResult -Update
$Days = "7"
$LogPath = "C:Users\529817\Temp"
$Date = Get-Date -format yyyy-MM-dd_HH-mm
$TargetFolder = "$TargetPath\$Date"
$LogFile = "$LogPath\ArchiveLog-$date.txt"
$TargetZipFile = "$TargetPath\$Date.zip"
$Activity = "Move files older than $Days days from $SourcePath to $TargetFolder"
Write-Verbose $Activity
$OldFiles = Get-Childitem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays( - $days)}
$Total = $Oldfiles.Count
$Current = 0
$OldFiles | ForEach {
$Current ++
$Filename = $_.fullname
Write-Progress -Activity $Activity -Status $FileName -PercentComplete ($Current / $Total * 100)
$Split = $FileName -split '\\'
$DestFile = $split[1..($split.Length - 1)] -join '\'
$DestFile = "$TargetFolder\$DestFile"
Try {
$null = New-Item -Path $DestFile -Type File -Force
$Null = Move-Item -Path $FileName -Destination $DestFile -Force -ErrorAction:SilentlyContinue
"Successfully moved $filename to $targetfolder" | add-content $LogFile
}
Catch {
$Err = $_.Exception.Message
Write-Error $Err
"Error moving $filename`: $Err " | add-content $LogFile
}
}
解决方案
你在这里有两个问题:
- 您的 zip 文件没有到达您想要的位置
- 相反,应该在拉链中的所有物品都在拉链应该去的地方。
让我们弄清楚为什么会发生这种情况,这样你就可以做你需要做的事情来让它工作。
问题 1
您有第 10 行,如下所示:
Compress-Archive -DestinationPath $ZipFileResult -Update
这会创建 Zip 文件,但您实际上并没有对这个文件做任何事情,因为我们没有看到$ZipFileResult
在代码中再次使用它。这就是为什么您的 zip 文件没有显示在您想要的位置的原因。
问题 2
该脚本的末尾有一个大块,您将文件明确复制到目录中,就在您不想要它们的地方。
Try {
$null = New-Item -Path $DestFile -Type File -Force
$Null = Move-Item -Path $FileName -Destination $DestFile -Force -ErrorAction:SilentlyContinue
"Successfully moved $filename to $targetfolder" | add-content $LogFile
}
如果您只想移动 Zip 文件,则可以缩短整个脚本。删除从第 19 行开始的所有内容,从这一行开始。
$OldFiles = Get-Childitem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays( - $days)}
相反,添加一个Move-Item
命令将该$ZipFileResult
文件复制到您希望它去的任何目录。
最后,有许多行不做任何事情并且可以删除,比如这一行$TargetZipFile = "$TargetPath\$Date.zip"