Home > Back-end >  how to Stop or exit if getting the specific error on powershell command
how to Stop or exit if getting the specific error on powershell command

Time:10-04

PS C:\Users\Administrator> Initialize-Tpm Initialize-Tpm : The device is not ready for use. (Exception from HRESULT: 0x800710DF) At line:1 char:1

  • Initialize-Tpm
  •     CategoryInfo          : NotSpecified: (Microsoft.Tpm.C...alizeTpmCommand:InitializeTpmCommand) [Initialize-Tpm], TpmWmiException
        FullyQualifiedErrorId : TpmError,Microsoft.Tpm.Commands.InitializeTpmCommand
    

CodePudding user response:

simply use try/catch:

try {
    #Set erroraction to stop to ensure any error is a terminating error
    Initialize-Tpm -ErrorAction:stop
}
Catch {
    #return error message and stop processing
    throw $_
}

Instead of throw you could also use return to stop the processing or exit (but exit will terminate the process).

You can also tell catch to react only on specific errors:

catch [exception]{
}

see: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.2

  • Related