powershell-4.0get-childitem

Excluding folder and contents when using get-child items -exclude not working


I want the script to go through a specific path and exclude one specific folder and its contents. I then want it to delete all .pdf files older than 3 days. The filtering and deletion works as expected, however i an having issues excluding the folder that I want to keep data in.

$older_than = "3" #days before current date
$path = "E:\Bookmark\Bookmarkers" #file path 
$excluded = "E:\Bookmark\Bookmarkers\VBMSArchive" #vbms documentation folder 
$ext = "*.pdf"  #file ext. to delete.
$cut_off = (Get-Date).AddDays(-$older_than) #Calculates the cut off date
Get-ChildItem -Path $path  -exclude $excluded -Recurse -File | Where-Object { $_.Name -like $ext }| Where-Object {$_.LastWriteTime -lt $cut_off} | Remove-Item -Force -Verbose #remove the desired files. 

The script still deleted the .pdf files in the excluded folder that are older than 3 days.


Solution

  • Here is how I resolved my issue. I set the filtered list of folders to a variable, then used the variable to enumerate the files and delete them.

    $older_than = "7" #days before current date
    $path = "E:\Bookmarking\Bookmarkers" #file path 
    Set-Location -Path $path #sets working directory to e:\bookmark\bookmarkers
    $excluded = "VBMSArchive" #vbms documentation folder 
    $ext = "*.pdf"  #file ext. to delete.
    $cut_off = (Get-Date).AddDays(-$older_than) #Calculates the cut off date
    $filteredList = Get-ChildItem -Path $path | where-Object {$_.Name -notlike $excluded}
    Get-ChildItem $filteredList -Recurse  -File | Where-Object { $_.Name -like $ext }| Where-Object {$_.LastWriteTime -lt $cut_off} | Remove-Item -Force -Verbose #remove the desired files.