加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

windows – 复制文件时如何在powershell中将错误输出到日志文件

发布时间:2020-12-13 22:34:11 所属栏目:Windows 来源:网络整理
导读:我正在尝试编写执行以下操作的power shell脚本: 检查远程计算机上的文件夹(计算机文本列表)是否存在,如果是,则将其删除. 将文件夹从远程共享复制到同一台计算机,如果错误输出到错误日志文件,如果没有,则输出到成功日志文件. 我已搜索但无法找到解决我看似简
我正在尝试编写执行以下操作的power shell脚本:

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

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

$computers=Get-Content C:pcs.txt
$source="RemoteShareRemoteFolder"
$dest="C$Program FilesDestination"


  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:logssuccess.log"}
Else
{Write-Output $computer | out-file -append -filepath "C:logsfailed.log"}

}

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

在运行for循环时,如何正确处理PowerShell中的错误?

解决方法

这是一个例子.

$array = @(3,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!"
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读