2016-07-27 48 views
0

的我有一個像下面的例子是除了X天以上已刪除的文件和記錄到文件中的記錄功能(寫日誌)cmdlet的:登錄cmdlet的輸出與日誌記錄功能的文件,而無需使用的foreach

$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的所有行動的過程?

+0

我應該問下面,爲什麼你要避免ForEach/ForEach-Object? – markg

回答

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 
    } 
} 
+0

hm thx,不認爲它可以很容易地把它變成一個foreach:/ – user1276012