4

我正在尝试编写一个执行以下操作的 powershell 脚本:

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

我已经搜索但无法找到解决我看似简单的问题的方法,请参阅下面的代码:

$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 文件中,无论它是否失败。

如何在通过 for 循环运行时正确处理 powershell 中的错误?

4

2 回答 2

5

这是一个例子。

$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!"
    }
}
于 2013-11-04T22:38:36.813 回答
4

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

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

于 2013-11-05T03:04:30.953 回答