Search code examples
powershell-4.0get-childitem

Get-ChildItem returns no items in script, but works from command line


I have a script that does some processing and then needs to delete files from a folder that haven't been modified for 10 days.

Firstly I get the date 10 days ago with:

$deleteDate = (Get-Date).AddDays(-10)

I then try and get the file list with:

$deleteFiles = Get-ChildItem -Path $destinationPath | Where-Object { $_.LastWriteTime -le $deleteDate }

However, this doesn't return any items (I output $deleteFiles.Length). If I run the exact same command, setting the variables first, from the powershell command line, it returns files.

I have tried adding the -Force parameter without luck.


Solution

  • This destination folder contains only files or files are in subfolders ?

    $del=Get-ChildItem -Path $destinationPath -recurse | Where-Object {!$_.PsIsContainer -and ($_.LastWriteTime -le $deleteDate) }
    

    This will list file in all subfolders -recurse and only files !$_.PsIsContainer

    This works for me:

    $destinationPath = "c:\temp"
    $deleteDate = (Get-Date).AddDays(-10)
    $del=Get-ChildItem -Path $destinationPath -recurse | Where-Object {!$_.PsIsContainer -and ($_.LastWriteTime -le $deleteDate) }
    $del.length
    

    And returns number of files.