PowerShell Robocopy capture error message

When I use robocopy with invalid source directory I get the following message returned from PowerShell. My question is is the error message "2021/12/09 01:55:41 ERROR 3 (0x00000003) Accessing Source Directory c:\artifactTempDir....The system cannot find the path specified."

Is this stored in any variable? i am just trying to capture these two lines from the entire message. enter image description here

Upvotes: 0

Views: 451

Answers (2)

Peter S
Peter S

Reputation: 41

You can use parameters like below. Then after running Robocopy, catching the errorcode in varible $lastexitcode.

See example:

$logfile = "C:\Tmp\RoboSync.log"
$RoboExe = "C:\Windows\System32\robocopy.exe"
$source = "C:\Tmp\from"
$destination = "C:\Tmp\to"

$param = @("$source", "$destination", "*.csv", '/s', '/MaxAge:7', '/DCOPY:DAT', '/COPY:DAT', '/R:10', '/W:20', '/Tee', '/np', "/unilog+:$logfile")

# Run
& $RoboExe $param

$result = Get-RobocopyResult -ExitCode $LASTEXITCODE

# Function to translate error code into text
function Get-RobocopyResult {
    param (
        [int]$ExitCode
    )
    switch ($ExitCode) {
        16 { return "***FATAL ERROR***" }
        15 { return "OKCOPY + FAIL + MISMATCHES + XTRA" }
        14 { return "FAIL + MISMATCHES + XTRA" }
        13 { return "OKCOPY + FAIL + MISMATCHES" }
        12 { return "FAIL + MISMATCHES" }
        11 { return "OKCOPY + FAIL + XTRA" }
        10 { return "FAIL + XTRA" }
        9  { return "OKCOPY + FAIL" }
        8  { return "FAIL" }
        7  { return "OKCOPY + MISMATCHES + XTRA" }
        6  { return "MISMATCHES + XTRA" }
        5  { return "OKCOPY + MISMATCHES" }
        4  { return "MISMATCHES" }
        3  { return "OKCOPY + XTRA" }
        2  { return "XTRA" }
        1  { return "OKCOPY" }
        0  { return "No Change" }
        default { return "Unknown exit code" }
    }
}

Upvotes: 0

mklement0
mklement0

Reputation: 437598

Assuming that robocopy writes its error messages to the stderr stream (which it should):

$stdout, $stderr = (robocopy ... 2>&1).Where({ $_ -is [string] }, 'Split')

$stderr now contains any stderr output (and $stdout contains the stdout output).

Upvotes: 1

Related Questions