0

I have a cmdlet like the following example to deleted files older than x days and a logging function (write-log) that logs to a file:

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

What I want to do is log what the cmdlet does to each processed file. In a normal foreach-loop I would add something like this to log the process

if($?){
    write-log -Info "File $item deleted successfully" #call my logging function that logs to a file
} else {
    write-log -Info "File $item could not be deleted" #call my logging function that logs to a file
}

How can I log all actions using my logging function and the above cmdlet?

1
  • I should have asked below, why are you avoiding ForEach/ForEach-Object? Commented Jul 27, 2016 at 18:16

1 Answer 1

1

Why not simply combine them into the same loop?

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | ForEach-Object {
    Remove-Item $_ -Force
    if($?){
        write-log -Info "File $($_.Name) deleted successfully" #call my logging function that logs to a file
    } else {
        write-log -Info "File $($_.Name) could not be deleted" #call my logging function that logs to a file
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

hm thx, didnt think that it could be that easy to turn it into a foreach :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.