使用日志记录功能将 cmdlet 输出记录到文件,而不使用 foreach

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

我有一个类似于以下示例的 cmdlet,用于删除早于 x 天的文件,以及一个记录到文件的日志记录功能(写入日志):

$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

我想要做的是记录 cmdlet 对每个已处理文件的操作。在正常的 foreach 循环中,我会添加类似这样的内容来记录过程

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
}

如何使用我的日志记录功能和上述 cmdlet 记录所有操作?

为什么不简单地将它们合并到同一个循环中呢?

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