user2725926
user2725926

Reputation: 3

Deleting old files using powershell

Hey guys so i wrote this script to auto delete files in the specified folder.

$oldTime = [int]25 # 0 days
$old2Time = [int] 10 
foreach ($path in "C:\Test") {
Write-Host "Trying to delete files older than days, in the folder $path" -    
ForegroundColor Green
# Write information of what it is about to do   
Get-ChildItem $path -Recurse -Include "*.txt", "*.docx", "*.xlsx" #| WHERE    
{($_.CreationTime -le $(Get-Date).AddDays($oldTime))} #| Remove-Item -Recurse -Force}
if ($_.CreationTime -le $(Get-Date).AddDays(-$oldTime)) 
{
Remove-Item -Recurse -Force
}
elseif ($_.CreationTime -le $(Get-Date).AddDays(-$old2Time))
{   
Remove-Item -Recurse -Force
}
}
# deleting the old files

It worked before when i had it just checking for a single time and deleting anything older. however now i would like it to check to see if any files older than a certain amount days exist then delete them. if not then check for older than another amount of days. but when i run it i get "cmdlet Remove-Item at command pipeline position 1 Supply values for the following parameters: Path[0]:"

anyone know what im doing wrong? Thanks

Upvotes: 0

Views: 3561

Answers (2)

Finzzownt
Finzzownt

Reputation: 380

I placed your day ranges in an array and iterate over these days. Add your days to the $dayList array and your paths to the $paths array. This should do what you want.

$daysList = @(25,10)
$paths = @("C:\Test")

function removeOldItems($days)
{
    $items = Get-ChildItem $path -Recurse -Include "*.txt", "*.docx", "*.xlsx" | WHERE {($_.CreationTime -le $(Get-Date).AddDays($oldTime))}
    if ($items)
    {
         $items | Remove-Item -Force
    }
    return $items
}


foreach($path in $paths)
{
    foreach ($days in $daysList)
    {
        Write-Host "Trying to delete files older than $days, in the folder $path" -ForegroundColor Green
        $items = @(removeOldItems($oldTime))
        if (!$items)
        {
            Write-Host "Did not remove anything."
        }
        else
        {
            Write-Host "Removed $($items.Count) items!"
        }
    }
}

Upvotes: 0

EBGreen
EBGreen

Reputation: 37740

You are calling Remove-Item but you never tell it what to remove. You need to give it the path/name of the file to remove. Also there is no reason to use the -Recurse parameter.

Upvotes: 3

Related Questions