I am trying to move files in directories by year from lastmodifiedtime and sub-directory by month from lastmodifiedtime.. it is giving itemnotfound error..
$sourcepath = 'c:\cameraroll\'
$targetPath = 'c:\cameraroll_organised\'
$files = Get-ChildItem $sourcepath -Recurse | where {!$_.PsIsContainer}
foreach ($file in $files)
{
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
$Directory = $targetPath "\" $year "\" $month
$file | Move-Item -Destination $Directory
}
CodePudding user response:
Just add condition to check if driectory exist or not before moving file try this
$sourcepath = 'c:\cameraroll\'
$targetPath = 'c:\cameraroll_organised\'
$files = Get-ChildItem $sourcepath -Recurse | where {!$_.PsIsContainer}
foreach ($file in $files)
{
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
$Directory = $targetPath "\" $year "\" $month
if (!(Test-Path $Directory)){
New-Item $directory -type directory
}
$file | Move-Item -Destination $Directory
}