I'm trying to move old files into folders based on creation date. The setup is that the script should check a folder for files older than 5 years and then put them in folders sorted by year with subfolders for each month.
$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
I get this error
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