cdouglas10683
cdouglas10683

Reputation: 147

Exception Logging in PowerShell

I am currently having an issue logging exceptions in my PowerShell script. I am trying to copy a file to C:\Windows\System32 and I want to add an error line to my log file if it errors. I have tried this two ways so far.

Example 1:

$LogPath = "C:\Test.txt
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Copy-Item $scriptPath\Devcon.exe C:\Windows\System32 -ErrorAction SilentlyContinue -ErrorVariable $Errors

Foreach($error in $Errors)
{
    add-content -Path $LogPath -Value $($error.Exception) -Force
}

Example 2:

$LogPath = "C:\Test.txt
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Try{
    Copy-Item $scriptPath\Devcon.exe C:\Windows\System32
}
Catch [System.Exception]
{
    add-content -Path $LogPath -Value "There was an error why trying to copy the file." -Force
    add-content -Path $LogPath -Value $Error -Force
}

I can add items to the log file so I know it's not a permissions issue with the file. What am I missing?

Upvotes: 3

Views: 854

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26414

I believe the error you are getting is non-terminating. This is why it does not end up in a catch block.

Try this instead of your Copy-Item line:

Copy-Item $scriptPath\Devcon.exe C:\Windows\System32 -ErrorAction Stop

Help on ErrorAction (MSDN).

Upvotes: 3

Related Questions