4

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:

$computers=Get-Content C:\pcs.txt
$source="\\RemoteShare\RemoteFolder"
$dest="C$\Program Files\Destination"


  foreach ($computer in $computers) {

        If (Test-Path \\$computer\$dest){
            Remove-Item \\$computer\$dest -Force -Recurse 
                }
    Copy-Item $source \\$computer\$dest -recurse -force -erroraction silentlycontinue

    If (!$error)
{Write-Output $computer | out-file -append -filepath "C:\logs\success.log"}
Else
{Write-Output $computer | out-file -append -filepath "C:\logs\failed.log"}

}

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?

2 Answers 2

5

Here's an example.

$array = @(3,0,1,2)

foreach ($item in $array)
{
    try
    {
        1/$item | Out-Null
        $computer | Add-Content -Path "C:\logs\success.log"
    }
    catch
    {
        "Error: $_" | Add-Content -Path "C:\logs\failed.log"
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

you can use $_.Message to get the exceptions message in the catch block.
@ChadCarisch Yes, I know. I was just trying to provide an example for him to follow.
4

Don't use $error, it always contains an array of recent error objects, even if the last command was successful. To check the results of the last command, use the $?, it will be false if the last command failed.

See about_Automatic_Variables for more details on these variables.

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.