Home > Back-end >  Powershell. Writing information to the log with and without an error
Powershell. Writing information to the log with and without an error

Time:10-04

I'm trying to get powershell to write information about the execution of an operation to a log file. 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"}

CodePudding user response:

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. 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 e.g.:

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:

$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 . - do I understand this correctly the filename is only a dot, nothing else?

CodePudding user response:

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}
  • Related