Powershell get files older than x days and move them Powershell get files older than x days and move them powershell powershell

Powershell get files older than x days and move them


There is no need to use "where" to test the extension as get-childitem does this for you. Although I would use the filter parameter (2nd positional parameter) in the case of a single extension to search for e.g.:

$date = (get-date).AddDays(-31)get-childitem \\server\folder *.pdf | where-object {$_.LastWriteTime -gt $date} |     move-item -destination \\server\folder\folder2

Btw using the filter parameter is also faster which maybe important when searching a network share.


One way is to add $_.Extension -eq ".pdf" to your where-object block so that you only grab those extensions.

get-childitem -path \\server\folder  | where-object {$_.extension -eq ".pdf" -and ($_.LastWriteTime -gt (get-date).AddDays(-31))} | move-item -destination C:\test\test

Also, if you want files older than one month, your date comparison needs to be -lt and not -gt

get-childitem -path \\server\folder  | where-object {$_.extension -eq ".pdf" -and ($_.LastWriteTime -lt (get-date).AddDays(-31))} | move-item -destination C:\test\test


Another way to do this is to specify the -Name flag and use wildcard for filename:

get-childitem -path \\server\folder -name "*.pdf" | where-object {$_.LastWriteTime -gt (get-date).AddDays(-31)} | move-item -destination \\server\folder\folder2