2

I am trying to eliminate the temporary script file (i.e. diskpart /s scriptFile) used to automate diskpart by replacing it with commands issued via a pipe, however I can't seem to figure out how to detect when diskpart throws an error. If you have a drive N: change the select vol n with a non-existent drive so diskpart will generate an error:

(
 (
  echo select disk 0
  echo list partition
  echo select vol n
 ) | diskpart
 set foundErr=1
 if errorlevel 0 if not errorlevel 1 set "foundErr="
 if defined foundErr goto :errorMsg
 echo Success!
 goto :EOF
)

 :errorMsg
 echo diskpart failed!
 goto :EOF 

pause  

I based the code above on this answer, but it's not working.

Is this even possible, or does the use of a pipe block or interfere with diskpart error detection?

Community
  • 1
  • 1
motech man
  • 51
  • 3
  • You do realise that `set` will also set `errorlevel`? "a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run" source http://ss64.com/nt/errorlevel.html – DavidPostill Jun 28 '16 at 11:46
  • I am using the cmd extension. I've read elsewhere that if, set, goto and a few other commands do NOT set errorlevel. However, in general I find the Windows .bat / .cmd language to be terrible, one of the worst for productive programming. In my 30+ years of IT work and all of the scripting languages I used or read about, Windows batch has to rank as one of the worst I've seen. After this project I will not use it again for anything significant if I can avoid it. – motech man Jun 28 '16 at 19:18
  • Yes, that would be because it was never designed to be a programming language in the first place. It's a batch interpreter, intended for very simple tasks, and almost certainly not an appropriate choice for what you're trying to do - plain old C would probably be my first choice, but if you *insist* on using a scripting language, try Powershell. – Harry Johnston Jun 29 '16 at 02:47

1 Answers1

0

I haven't tested it yet. but this should work:

(
 (
  echo select disk 0
  echo list partition
  echo select vol n
 ) | diskpart 
 if "%errorlevel%"=="0" (
if not "%errorlevel%"=="1" 
(
set "foundErr="
)
) Else set foundErr=1
 if defined foundErr goto errorMsg
 echo Success!
 goto :EOF
)

 :errorMsg
 echo diskpart failed!
 goto :EOF 

pause