【问题标题】:How to catch machine name on copy-item error?如何在复制项错误时捕获机器名称?
【发布时间】:2014-05-06 15:59:45
【问题描述】:

我正在尝试在多台远程 Windows 机器上写入文件并删除文件。如果机器不可用,即。不在线我想在错误日志中捕获它,以便我有一个有问题的机器名称列表发送给帮助台。它可能很难看,但我已经接近了一些有用的东西。任何澄清将不胜感激。

$from="D:\whatever\machinfo"
$to="\\$machine\c\\scripts\"
output_file="D:\whatever\reports\$machine_writeerror.txt"

foreach($machine in(gc d:\whatever\machinfo\testworkstations.txt))
    {
    $machine
    IF (!$to) 
    {
    Copy-Item D:\whatever\machinfo\010RunGetmachinfo.bat \\$machine    \c\scripts -verbose
    # $errormsg="destination not found"
    $machine > output_file
    }
    ELSE
    {
    # DO NOTHING
    Remove-Item \\$machine\c\scripts\000dontrun.bat
    }
    }  

好的,我已经重写了这个,但我做的不对。我想要一个唯一的错误文件,其中包含每个机器连接失败的单个文件或一个包含所有无法连接到的机器的计算机名的文件。我认为以下内容很接近(但不正确)。

$logfile="D:\Projects\StoreControls\machinfo\reports\"+$machine+"_writeerror.txt"

foreach($machine in(gc d:\projects\StoreControls\machinfo\testworkstations.txt))
   {
   $machine
   If ( (Test-Connection -Computername $machine -Quiet -Count 1) -eq "False"){
   $machine > $logfile}
   Else{
   Remove-Item \\$machine\c\scripts\tasks\000dontStart.bat
   Copy-Item D:\Projects\StoreControls\machinfo\010RunPCsNServersGetmachinfo.bat \\$machine\c\scripts\tasks\ 
   }
   }

在阅读有关测试连接的更多信息后,将“False”更改为 $False。作品!谢谢!

【问题讨论】:

    标签: powershell error-handling copy-item


    【解决方案1】:

    您可以通过测试automatic variable$?来测试命令的正确执行

    所以你可以使用类似的东西

    Copy-Item D:\whatever\machinfo\010RunGetmachinfo.bat \\$machine\c\scripts 
    if($? -eq $false){
        # copy has failed
        "Copy error on $machine" |out-file d:\whatever\reports\$machine_writeerror.txt
    
    }
    

    顺便说一句,更有效的方法是 ping 主机并查看它是否还活着:

    if ( (Test-Connection -ComputerName $machine -Quiet  -Count 1) -eq  $false){
        #host not available
    
    }
    

    【讨论】:

    • 关闭但脚本在错误例程中失去了#machinfo(即计算机名)的含义。我希望机器名称作为错误文件。 $logfile="D:\whatever\reports\"+$machine+"_writeerror.txt" foreach($machine in(gc d:\whatever\testworkstations.txt)) { $machine Copy-Item D:\whatever\010RunGetmachinfo. bat \\$machine\c\scripts\ If($? -eq $false){ $machinfo > $logfile} Remove-Item \\$machine\c\scripts\000dontrun.bat }
    • 简而言之,如果文件复制失败,我想编写一个包含机器名称的错误文件。即,如果我尝试将文件写入 s456720 并且机器处于脱机状态,我想要一个包含该名称的文件。最后我会把它们都收集起来。
    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多