如何在复制文件时将错误输出到PowerShell中的日志文件

我想写一个powershell脚本,执行以下操作:

  1. 检查远程计算机上的文件夹(计算机的文本列表)是否存在,如果这样删除。
  2. 将远程共享中的文件夹复制到同一台机器上,如果有错误日志文件输出,则输出到成功日志文件。

我已经search,但一直无法find解决我的看似简单的问题,请看我的代码如下:

$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"} } 

目前,当脚本运行时,无论失败与否,所有内容都将放入failed.log文件中。

如何正确处理PowerShell中的错误,而通过for循环运行?

这是一个例子。

 $array = @(3,0,1,2) foreach ($item in $array) { try { 1/$item | Out-Null Write-Host "$item is okay" } catch { Write-Host "There was an error! Can't divide by $item!" } } 

不要使用$error ,即使最后一个命令成功,也总是包含最近错误对象的数组。 要检查最后一个命令的结果,请使用$? 如果最后一个命令失败,它将是错误的。

有关这些变量的更多详细信息,请参阅about_Automatic_Variables 。