如何使用 .LastWriteTime 和 (get-Date).将数据移动到新的年/月文件夹结构中的月份



我对Powershell相当陌生,任务是清理存档服务器。我正在尝试创建一个脚本,通过查看Powershell中的LastWriteTime将文件移动到Year\Month文件夹结构中。

我有以下内容,但是我不知道如何让它查看文件的编辑月份?

$Path = "D:Data"
$NewPath = "D:ArchiveData"
$Year = (Get-Date).Year
$Month = (Get-Date).Month
New-Item $NewPath -name $CurrentYear -ItemType Directory
New-Item $NewPath$Year -Name $Month -ItemType Directory
Get-ChildItem -path $Path | Where-Object {$_.LastWriteTime -Contains (Get-Date).month} | Move-Item -Destination "$NewPath$Year$Month"

关于我如何做到这一点的任何想法将不胜感激?

谢谢

-contains

用于查看数组是否包含项目;它不适合这里。

-eq是您需要的。根据您的变量$Month,您只需要获得您关心的部分(即月份(:

($_.LastWriteTime).Month -eq (Get-Date).month

我想我会从另一端解决这个问题。可以在需要时创建目录。

如果对正确移动文件感到满意,请从Move-Itemcmdlet 中删除-WhatIf

$Path = 'C:srct'
$NewPath = 'C:srctarch'
Get-ChildItem -File -Path $Path |
ForEach-Object {
$Year = $_.LastWriteTime.Year
$Month = $_.LastWriteTime.Month
$ArchDir = "$NewPath$Year$Month"
if (-not (Test-Path -Path $ArchDir)) { New-Item -ItemType "directory" -Path $ArchDir | Out-Null }
Move-Item -Path $_.FullName -Destination $ArchDir -WhatIf
}

最新更新