How to output errors to a log file in powershell when copying files

Question:

I am trying to write a powershell script that does the following:

  1. Check to see if a folder on a remote machine(text list of computers) exists, if so delete it.
  2. Copy a folder from a remote share to the same machine and if there is an error output to an error log file, if not, output to a success log file.

I have searched but have been unable to find a solution to my seemingly simple problem, please see my code below:

Currently, when the script runs, everything is getting put in the failed.log file, regardless of if it fails or not.

How can I properly handle errors in powershell, while running through a for loop?

Answer:

Here’s an example.

Source:

How to output errors to a log file in powershell when copying files by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply