Returning an error code from CMD to Powershell

前端 未结 3 1667
悲&欢浪女
悲&欢浪女 2021-01-18 11:19

I\'m working on a Mssql install script and I want to get the results of a silent mssql installation. In my PowerShell script I run this command:

$result = (s         


        
相关标签:
3条回答
  • 2021-01-18 11:57

    This is how you do it: start is actually an alias Start-Process, so you have to look at it's documentation, which is a lot different than cmd.exe's start. So you can do this:

    (Start-Process -FilePath "cmd.exe /c ..." -Wait -Passthru).ExitCode
    

    So easy!

    0 讨论(0)
  • 2021-01-18 11:58

    Too late maybe but does this help?

    start /WAIT cmd.exe /C "YOUR-COMMAND-HERE" & if errorlevel 1 echo 'error occurred'
    

    you can also explicitly return an error code like this:

    start /WAIT cmd.exe /C "YOUR-COMMAND-HERE & exit MY-ERROR-CODE" & if errorlevel 1 echo 'error occurred'
    
    0 讨论(0)
  • 2021-01-18 11:59

    An alternative to Start-Process is the more syntactically terse call operator &.

    & cmd.exe /c 'ping.exe doesnotexist && exit 0 || exit 1'
    

    The exit code will be contained in the built-in variable $LASTEXITCODE so:

    Write-Host $LASTEXITCODE
    

    This will contain the exit code of the program run so you don't necessary have to run it with CMD.exe you could just do:

    & ping.exe doesnotexist ; Write-Host $LASTEXITCODE
    

    Applied to your command line program:

    & cmd.exe /c 'D:\SQL2008R2\SQL2008R2\setup.exe /CONFIGURATIONFILE=sqlconfig.ini && exit 0 || exit 1'
    

    Or just:

    & D:\SQL2008R2\SQL2008R2\setup.exe /CONFIGURATIONFILE=sqlconfig.ini
    

    In both cases $LASTEXITCODE should be 0 for success, non-zero otherwise (if the external program was written correctly).

    0 讨论(0)
提交回复
热议问题