Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

powershell - Checking exit code of last command using "if" statement

I want to check the status of last command and based on the exit code, the commands will be executed further.

The last command execute was:

$hiveJob = Start-AzureHDInsightJob -Cluster $clusterName -JobDefinition  $hiveJobDefinition
Wait-AzureHDInsightJob -Job $hiveJob -WaitTimeoutInSeconds 5400
Get-AzureHDInsightJobOutput -Cluster $clusterName -JobId $hiveJob.JobId -StandardOutput

The output is:

Cluster         : crmhdinsight  
ExitCode        : 0  
Name            : Hive: show tables;  
PercentComplete :   
Query           : show tables;  
State           : Completed  
StatusDirectory : 7dc4b67f-99a9-4c6b-a9f3-ffe8b4e29c7e  
SubmissionTime  : 7/28/2014 11:44:04  
AMJobId         : job_1406103802152_0053  

Now, I want to execute further commands only if the exitcode is zero. How do I write an if statement for this condition?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're talking about "exit code". If you mean $LastExitCode automatic variable, it is only populated when you call windows program, RAR for example:

$x=rar
$LastExitCode

It will return exit code 7 (if you have RAR installed).

cmdlets, however, don't fill this variable. You can use another automatic variable $? for this:

$x=gci
$?

It only gives $True if command completed successfully or $False if there was an error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...