Search code examples
powershellbatch-filecmdbatch-processing

Run command If fails then run the other one if success then end


I'm trying to find a way to uninstall maya2019 from all studio workstation. We have 3 versions of maya2019 with different uninstall commands:

"C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {D4BE10F2-3E2D-4120-863A-765623D53264} /M MAYA /LANG en-us /q

"C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {77067FD9-800C-48B4-803D-569642ADABC5} /M MAYA /LANG en-us /q

"C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42} /M MAYA /LANG en-us /q

I need to make a script that runs the commands, if one fails then it runs the the next one down, if it succeed the it exits with complete and stops.

Right now I have this:

if "C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {D4BE10F2-3E2D-4120-863A-765623D53264} /M MAYA /LANG en-us /q; then
    echo success && exit
else
if "C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {77067FD9-800C-48B4-803D-569642ADABC5} /M MAYA /LANG en-us /q; then
    echo success && exit
else
if "C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe" /P {77067FD9-800C-48B4-803D-569642ADABC5} /M MAYA /LANG en-us /q; then
    echo success && exit

but I'm not sure if I'm going in the right direction?

Thanks for your help


Solution

  • As suggested by Theo in the comments on the question, a more efficient solution would be to query the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for uninstallation command lines based on the GUIDs in your commands.

    This answer provides pointers as to how to do that.

    If that is not an option, here'a PowerShell solution:

    foreach ($guid in '{D4BE10F2-3E2D-4120-863A-765623D53264}', 
                      '{77067FD9-800C-48B4-803D-569642ADABC5}', 
                      '{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}') {
    
      $exe = 'C:\Program Files\Autodesk\Maya2019\Setup\Setup.exe'
    
      $ps = Start-Process -PassThru -Wait $exe "/P $guid /M MAYA /LANG en-us /q"
    
      if ($ps.ExitCode -eq 0) { "Success"; exit 0 }
    
    }
    
    Write-Warning "Uninstallation failed."
    exit $ps.ExitCode
    

    Start-Process -PassThru -Wait starts the installer process, waits for its termination, and then returns a System.Diagnostics.Process instance representing the terminated process, whose exit code (.ExitCode) can then be examined. An exit code of 0 signals success, any other value failure.