复制项目后出现包含详细信息的 Powershell 错误消息

Lyn*_*ynn 3 powershell

我是 Powershell 新手,目前正在处理需要将不同文件复制到一台服务器的案例。将文件复制到服务器后,结果将返回到日志文件(成功或失败)。

对于失败的复制,错误消息给出了失败原因,例如服务器不可用或用户无权访问。系统错误信息。

我尝试使用 $errorMessage 但它不起作用,有人可以告诉我该怎么做吗?

块引用

    $dest = "\\server1\folder\as00.LOG"
    $source_path = "\\server2\folder\as00.LOG", "\\server3\folder\as00.LOG  "
    $logProgress = "\\server1\folder\CopyLogs.txt"

    foreach ($Path in $source_path) {    
     If (Test-Path $dest ){
     $i = 1
     While (Test-Path $dest )
     {  $dest = "\\server1\folder\as00$i.LOG"
        $i += 1}
     }else{ New-Item -ItemType File -Path $Dest -Force}

     Copy-Item -Path $Path -Destination $dest -Recurse -Force -errorAction silentlyContinue   
     if($? -eq $false) {
        $ErrorMessage = $_.Exception.Message
        echo "Date: $((Get-Date).ToString()). Status: Copy Failure - $ErrorMessage" | out-file -append $logProgress}
     else{
        echo "Date: $((Get-Date).ToString()). Status: Successfully copied" | out-file -append $logProgress}
      }  
Run Code Online (Sandbox Code Playgroud)

非常感谢!林恩

gms*_*man 5

为了$ErrorMessage

$ErrorMessage = $Error[0].Exception.Message    # probably
$ErrorMessage = $Error[0].ErrorDetails.Message # less likely
Run Code Online (Sandbox Code Playgroud)

对于if($?,我建议使用标准Try/ Catch-ErrorAction Stop是必需的,因为

try{
    Copy-Item -Path $Path -Destination $dest -Recurse -Force -ErrorAction Stop

    # if the script gets to this part, Copy-Item did not error
    echo "Date: $((Get-Date).ToString()). Status: Successfully copied" | out-file -append $logProgress
}catch{
    # what to do if an error is encountered:
    $ErrorMessage = $Error[0].Exception.Message
    echo "Date: $((Get-Date).ToString()). Status: Copy Failure - $ErrorMessage" | out-file -append $logProgress}
}
Run Code Online (Sandbox Code Playgroud)

相关: 如何捕获和打印PowerShell异常消息