Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read error code returned from sc.exe command

How to read the error code returned from sc.exe in powershell?

I have below code

sc.exe create backupService BinPath= $binPath

sc.exe start backupService 

When executed, below is shown in console which is expected as the service is already running. I want to know how to read the error codes e.g. 1073 or 1056 in powershell for sc.exe output?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[SC] CreateService FAILED 1073:

The specified service already exists.

[SC] StartService FAILED 1056:

An instance of the service is already running.

>Solution :

Powershell sets an Automatic Variable called $LastExitCode which contains the exit code of the last external program – see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.2#lastexitcode

Your code would be something like this:

sc.exe create backupService BinPath= $binPath
if( $LastExitCode -ne 0 )
{
    # handle error
}

sc.exe start backupService
if( $LastExitCode -ne 0 )
{
    # handle error
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading