Question:
I am trying to write a powershell script that does the following:
- Check to see if a folder on a remote machine(text list of computers) exists, if so delete it.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$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?
Answer:
Here’s an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$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" } } |