I am trying to write a powershell script that does the following:
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?
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"
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With