Home > front end >  How to add error logging to PowerShell script
How to add error logging to PowerShell script

Time:05-25

I'm new to PowerShell scripts and would like to add error logging to the script below. The script is sending *.txt files to an FTP server.

How can I improve the error logging in this script? I'd like to catch any potential errors that might be triggered and maybe email them to an email address.

Right now, it's giving me the following error "Cannot find a variable with the name 'MyTestSession'." Why is this?

Import-Module PSFTP
[string] $User = 'testuser'

[string] $LocalFolder ='c:\EDI\Export\'
[string] $BackupFolder = 'C:\EDI\Backup\'
[string] $RemoteFolder ='/Inbound' 
[string] $FTPServ = '00.000.00.000'

[object] $objCred = $null
[System.Security.SecureString] $Pw

$Pw= ConvertTo-SecureString -String "2}bIed_d" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($User, $Pw)

$GetFiles=Get-ChildItem -Filter *.txt -Path $LocalFolder

if ($null -ne $GetFiles) {

    Set-FTPConnection -Credentials $objCred -Server $FTPServ -Session MyTestSession -UsePassive -UseBinary
    $Session = Get-FTPConnection -Session MyTestSession 

    foreach ($i in $GetFiles)
    {
        $timestamp=(Get-Date).tostring("MMddyyyyhhmmss")
        $NewFile = $i.FullName -Replace ".txt", ".$timestamp.txt"
        Rename-Item -Path $i.FullName -NewName $NewFile
        Add-FTPItem -Session $Session -Path $RemoteFolder -Overwrite -LocalPath $NewFile
        move-Item $NewFile -Destination $BackupFolder
        set-content C:\EDI\FTPScripts\Errors\Export.log $error
    }
}

CodePudding user response:

Your question is asking for assistance to improve error logging in your script. I will point you in the right direction to get you started.

In order to log or report an error, you first need to capture the error. This is called error handling. The most common way to handle a PowerShell error is using the try/catch blocks. The catch block is only invoked when the error is a Terminating Error. There are two types of errors in PowerShell, Terminating and Non-Terminating. The difference between the two, in a nutshell, is that Terminating errors will throw an error and cause your script to stop running if not handled and Non-Terminating errors will throw an error but will continue to run.

In order to handle Non-Terminating errors in a try/catch block, you must tell PowerShell to treat it as a Terminating error. There are several ways to do this but the most popular approach is to use the common cmdlet parameter "ErrorAction". This approach only works if an error is being thrown by a PowerShell Cmdlet. Another common way is to use the Preference Variable "ErrorActionPreference" (Ex: $ErrorActionPreference = "Stop"). Preference Variables are environment/script wide meaning if you set ErrorActionPreference to stop once in your script, all errors after it's set will be treated as Terminating errors.

Note: You're using $error when you call Set-Content. $Error is an Automatic Variable which is a collection or more specifically an ArrayList that contains the most recent errors in your PowerShell session. Since you're calling Set-Content in your foreach loop, consequently you will likely log the same exact errors multiple times. I'm assuming this is not intentional. A good practice is to avoid using $Error in your scripts in favor of using try/catch blocks whenever possible.

At this point you should have a decent understanding of errors and how to handle them, now you need to log or report them. Take what you've learned about try/catch blocks and implement them in your script.

This is just an example of how you could use a try/catch block with your Move-Item Cmdlet:

try {
    Move-Item $NewFile -Destination $BackupFolder    
}
catch [UnauthorizedAccessException] {
    
    # All errors that are of type "UnauthorizedAccessException" are captured here.    
    Set-Content -Path 'C:\EDI\FTPScripts\Errors\UnauthorizedAccessExceptionExport.log' -Value $_.Exception.Message
}
catch [ItemNotFoundException] {

    # All errors that are of type "ItemNotFoundException" are captured here.    
    Set-Content -Path 'C:\EDI\FTPScripts\Errors\ItemNotFoundExceptionExport.log' -Value $_.Exception.Message
}
catch {

    # All errors that are not of type UnauthorizedAccessException or ItemNotFoundException are capture here
    Set-Content -Path 'C:\EDI\FTPScripts\Errors\Export.log' -Value $_.Exception.Message
}
  • Related