简体   繁体   English

Powershell.向日志写入信息有错和无错

[英]Powershell. Writing information to the log with and without an error

I'm trying to get powershell to write information about the execution of an operation to a log file.我试图让 powershell 将有关操作执行的信息写入日志文件。 There is a folder with logs, it is necessary that the script delete files older than a certain number of days from the folder (implemented) and record information about the deletion of files or the absence of files in the folder (in case of an error when executing the script).有一个带有日志的文件夹,脚本必须从文件夹中删除超过一定天数的文件(已实现)并记录有关文件删除或文件夹中文件缺失的信息(以防出错执行脚本时)。 Now the script writes information to the log about the absence of files, then if they are.现在脚本将有关文件缺失的信息写入日志,如果存在的话。 Tell me what to do wrong?告诉我哪里做错了? The text is as follows:正文如下:

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

In principle $error is a automatic variable containg all errors occured within the current session. From my point of view its a better approach to use try/catch to handle errors.原则上 $error 是一个自动变量,包含当前 session 内发生的所有错误。从我的角度来看,使用 try/catch 处理错误是一种更好的方法。 By doing so you can specify the error message to write to the logfile that matches the error, instead of writing the same error message for any kind of errors eg:通过这样做,您可以指定要写入与错误匹配的日志文件的错误消息,而不是为任何类型的错误写入相同的错误消息,例如:

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
}

But back to your example, you could do:但回到你的例子,你可以这样做:

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

ok based on the comment you could go this route:好的,根据评论,您可以 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
}

Currently the code does not filter for '.'目前代码不过滤“。” like in your sample: /m.就像在你的样本中一样: /m. - do I understand this correctly the filename is only a dot, nothing else? - 我是否理解正确,文件名只是一个点,没有别的?

The script has earned in the following form:该脚本以以下形式获得:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM