user3331975
user3331975

Reputation: 2825

checking the status of command executed successfully

Sorry I am a newbie in PowerShell. I am running a script which executes some commands to copy files from a system.. Is there a way to capture the status of the command whether it completed successfully before moving to the next command?

For example:

$scp_cmd = "scp.exe -a [email protected]:/files/repo1 /repo1"
$rsync_cmd = "rsync.exe -tvP [email protected]:/files/repo2 /repo2"
Invoke-Expression $scp_cmd

# How do we check whether the command completed successfully?

Invoke-Expression $rsync_cmd

# How do we check whether the command completed successfully?

Upvotes: 1

Views: 3631

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

Use the $LASTEXITCODE automatic variable. It works both with Invoke-Expression and the & call operator:

$rsync_cmd = "rsync.exe -tvP [email protected]:/files/repo2 /repo2"
Invoke-Expression $rsync_cmd

if($LASTEXITCODE)
{
    # exit code from rsync was not 0
}

Upvotes: 4

Related Questions