Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 560
Bajan Avatar asked Jan 11 '23 23:01

Bajan


2 Answers

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"
    }
}
like image 132
crownedjitter Avatar answered Jan 18 '23 18:01

crownedjitter


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.

like image 41
zdan Avatar answered Jan 18 '23 18:01

zdan