Home > OS >  Powershell delete multiple file extensions from multiple folders
Powershell delete multiple file extensions from multiple folders

Time:10-26

I am trying to delete .txt and .pdf files older than 7 days from multiple folders on a drive. I am not getting any errors but it doesn't seem to be working as I check the folders in explorer and they are still there unchanged.

$rootFolder = 'D:\Folder1\Folder2\'
$folders = 'FolderA\FolderA1\','FolderB\','FolderC1\FodlerC1\','FolderD\FolderD2\FolderD3\'

foreach($folder in $folders){
    $fullPath = ( $rootFolder   $folder   ('*.txt*','*.pdf*'))

    Get-ChildItem –Path $fullPath -include ('*.txt', '*.pdf') -recurse |  Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-7))} | Remove-Item -recurse -verbose

}

Also, would putting the extensions in a variable be better?

$rootFolder = 'D:\Folder1\Folder2\'
$folders = 'FolderA\FolderA1\','FolderB\','FolderC1\FodlerC1\','FolderD\FolderD2\FolderD3\'
$files = '.txt','.pdf'

foreach($folder in $folders){
    $fullPath = ( $rootFolder   $folder   $files)

    Get-ChildItem –Path $fullPath -include $files -recurse |  Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-7))} | Remove-Item -recurse -verbose

}

CodePudding user response:

You definition of $fullpath seems to be incorrect. Using following construct does the trick:

foreach ($folder in $folders) {
   $fullpath = $rootfolder   $folder   '*'
   get-childitem -path $fullpath -Include ('*.txt','*.pdf')
}

See official documentation example 4.

  • Related