[英]Powershell. Writing information to the log with and without an error
我試圖讓 powershell 將有關操作執行的信息寫入日志文件。 有一個帶有日志的文件夾,腳本必須從文件夾中刪除超過一定天數的文件(已實現)並記錄有關文件刪除或文件夾中文件缺失的信息(以防出錯執行腳本時)。 現在腳本將有關文件缺失的信息寫入日志,如果存在的話。 告訴我哪里做錯了? 正文如下:
if ($error) {"No files found" *>> "D\TEST\Log $(gat-date -f dd-MM-yyy).txt"}
else {"Files deleted" *>> "D\TEST\Log $(gat-date -f dd-MM-yyy).txt"}
原則上 $error 是一個自動變量,包含當前 session 內發生的所有錯誤。從我的角度來看,使用 try/catch 處理錯誤是一種更好的方法。 通過這樣做,您可以指定要寫入與錯誤匹配的日志文件的錯誤消息,而不是為任何類型的錯誤寫入相同的錯誤消息,例如:
try {
#do someting
"Did something successfully" | set-content -path $logfilePath -Append -Force -Confirm:$false
}
Catch {
#gets executed if a terminating error occured
write-error "Failed to do something, Exception: $_"
"Failed to do something, Exception: $_" | set-content -path $logfilePath -Append
}
但回到你的例子,你可以這樣做:
$date = get-date -Format dd-MM-yy
$logFilePath = "D\TEST\Log_$date.txt"
If ($error){
"No files found" | set-content -path $logfilePath -Append -Force -Confirm:$false
}
Else {
"Files deleted" | set-content -path $logfilePath -Append -Force -Confirm:$false
}
好的,根據評論,您可以 go 這條路線:
$date14daysBack = (get-date).AddDays(-14)
$date = Get-Date -Format dd-MM-yyyy
$LogfilePath = "D:\TEST\Log_$date.txt"
try {
#try to map drive, if something goes wrong stop processing. You do not have to escape the $ if you use single quotes
New-PSDrive -Name "E" -PSProvider "FileSystem" -Root '\\Computer\D$\TEST' -Persist -ErrorAction:Stop
}
Catch {
"Failed to map drive '\\Computer\D$\TEST' - Exception $_" | Set-Content -Path $logfilePath -Append -Force
throw $_
}
try {
#I replaced forfiles and the delete operation with the powershell equivalent
$files2Remove = get-childitem -path E:\ -recurse | ?{$_.LastWriteTime -ge $date14daysBack}
$null = remove-item -Confirm:$false -Force -Path $files2remove.FullName -ErrorAction:stop
}
Catch {
"Failed to delete files: $($files2remove.FullName -join ',') - Exception: $_" | Set-Content -Path $logfilePath -Append -Force
}
#If files were found
If ($files2Remove){
"Files deleted, count: $($files2remove.count)" | Set-Content -Path $logfilePath -Append -Force
}
Else {
"No files found" | Set-Content -Path $logfilePath -Append -Force
}
目前代碼不過濾“。” 就像在你的樣本中一樣: /m.
- 我是否理解正確,文件名只是一個點,沒有別的?
該腳本以以下形式獲得:
#cleaning up errors
$Error.Clear()
#days storage
$int = 11
#connecting a network drive
New-PSDrive -Name "E" -PSProvider "FileSystem" -Root "\\Computer\D`$\TEST" -Persist
#deleting files
FORFILES /p E:\ /s /m *.* /d -$int /c "CMD /c del /Q @FILE"
#disabling a network drive
Remove-PSDrive E
#recording information in the log
$date = Get-Date -Format dd-MM-yyyy
$LogfilePath = "D:\TEST\Log_$date.txt"
(Get-Date) >> $LogfilePath
if ($Error){"No files found" | Add-content -path $LogfilePath -Force -Confirm:$false}
Else {"Files deleted" | Add-Content -path $LogfilePath -Force -Confirm:$false}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.