我正在尝试根据创建日期将旧文件移动到文件夹中。设置是脚本应检查文件夹中是否存在5年以上的文件,然后将其放入按年份排序的文件夹中,每个月都有子文件夹。
$SourceDir = "C:\Test"
$DestinationDir = "C:\Archive\Test\"
$limit = (Get-Date).AddYears(-5)
$files = Get-ChildItem $SourceDir * | Where-Object {
!$_.PSIsContainer -and $_.CreationTime -lt $limit
}
foreach ($file in $files) {
$Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory)) {
New-Item $directory -Type Directory
}
Move-Item $file.FullName $Directory
我收到此错误
PS C:\Scripts> .\SortIntoMonths5Year.ps1 You cannot call a method on a null-valued expression. At C:\Scripts\SortIntoMonths5Year.ps1:11 char:69 + $Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString <<<< ('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM') + CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull Test-Path : Cannot bind argument to parameter 'Path' because it is null. At C:\Scripts\SortIntoMonths5Year.ps1:13 char:16 + if (!(Test-Path <<<< $Directory)) + CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand Move-Item : Cannot bind argument to parameter 'Path' because it is null. At C:\Scripts\SortIntoMonths5Year.ps1:17 char:10 + Move-Item <<<< $file.FullName $Directory + CategoryInfo : InvalidData: (:) [Move-Item], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand
答案 0 :(得分:0)
自己修复
$SourceDir = "C:\Test"
$DestinationDir = "C:\Archive\Test\"
$files = get-childitem $SourceDir * | Where-Object {$_.LastWriteTime -lt (Get-Date).AddYears(-5)}
#$files = get-childitem $SourceDir *
foreach ($file in $files)
{
$Directory = $DestinationDir + "" + $file.LastWriteTime.Date.ToString('yyyy') + "\" + $file.LastWriteTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
Move-Item $file.fullname $Directory
}