Warm tip: This article is reproduced from serverfault.com, please click

Error-Handle powershell command in Batch File

发布于 2020-11-28 03:13:29

I have not been able to figure out how I would be able to get this to work.

I want this to extract zip like it to extract zip, but if it fails (Picture of error) I want it to delete the zip and curl it again.

The reason it would give an error is for corrupt zip, it is if the user closes the program during the initial zip install.

if EXIST "%UserProfile%\Downloads\100 Player Among US.zip" (
        echo "---Zip Detected, Extracting it now---"
        powershell -Command "Expand-Archive -Force '%UserProfile%\Downloads\100 Player Among US.zip' '%UserProfile%\Downloads\'"

        if There is an error  (
        DEL "%UserProfile%\Downloads\100 Player Among US.zip"
        echo "---Corrpupted Zip, I'm installing it again---"
        curl "link"
        )
    )
Questioner
Wolfhound905
Viewed
0
zett42 2020-11-28 17:59:35

To be able to handle the Powershell error in the batch script, you must return a non-zero exit code from Powershell in case of an error.

Powershell returns a non-zero exit code in these cases:

  • The script is terminated using the exit N statement, where N specifies a non-zero exit code.
  • A terminating error is not catched, so it "leaves" the script.
  • Syntax error in the script, e. g. invalid command.

By default, Expand-Archive causes a non-terminating error when extraction fails. We can turn that into a terminating error by passing common parameter -ErrorAction Stop or by setting preference variable $ErrorActionPreference = 'Stop' befor calling the command.

Example using -ErrorAction parameter:

powershell -Command "Expand-Archive -ErrorAction Stop -Force '%UserProfile%\Downloads\100 Player Among US.zip' '%UserProfile%\Downloads\'"
if ERRORLEVEL 1 (
   :: Handle the error
)

Example using $ErrorActionPreference:

powershell -Command "$ErrorActionPreference='Stop'; Expand-Archive -Force '%UserProfile%\Downloads\100 Player Among US.zip' '%UserProfile%\Downloads\'"
if ERRORLEVEL 1 (
   :: Handle the error
)

Setting the $ErrorActionPreference variable can simplify scripts that run multiple commands.