Search code examples
windowspowershellpowershell-cmdlet

Log cmdlet output to file with logging function without use of foreach


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?


Solution

  • 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
        }
    }