Home > Back-end >  How to read error code returned from sc.exe command
How to read error code returned from sc.exe command

Time:12-07

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?

[SC] CreateService FAILED 1073:

The specified service already exists.

[SC] StartService FAILED 1056:

An instance of the service is already running.

CodePudding user response:

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