3

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?

1
  • 1
    Approach 1 will not work with those variable names. $error is a reserved automatic variable name that stores the global list of errors, you can't use it as a loop variable. In general, @Neolisk is correct, you need to set ErrorAction to Stop to force. If you change your variable names (e.g. foreach( $err in $errors )), you might still be able to use overall approach #1, if you like. Commented Jul 8, 2013 at 17:42

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.