0

我有一个类似于以下示例的 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 记录所有操作?

4

1 回答 1

1

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

$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
    }
}
于 2016-07-27T18:13:14.387 回答