Lynn
Lynn

Reputation: 33

Powershell error message after copy-item with details

I'm new to Powershell and currently working on a case need to copy different files to one server. After copy the file to server the result will return to the Log files (successful or fail).

For the failed copy the error message with gives the fail reason such as server is not available or user has no access. The system error message.

I tried to use $errorMessage but it didn't work, could anyone show me how to do it please?

Blockquote

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

Many thanks! Lynn

Upvotes: 3

Views: 6732

Answers (1)

G42
G42

Reputation: 10019

For $ErrorMessage:

$ErrorMessage = $Error[0].Exception.Message    # probably
$ErrorMessage = $Error[0].ErrorDetails.Message # less likely

For if($?, I recommend using the standard Try/Catch. -ErrorAction Stop is required because

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

Related: How to capture and print PowerShell exception message

Upvotes: 5

Related Questions