问题
I found this code here --> ::Check if the path is File or Folder using batch
But I find it hard to read and want to simplify it/break it apart. I'm not sure how to do this, I tried the below and a few variations to no avail. Can anybody help? Thanks!
This code works:
@Echo Off
Set "ATTR=D:\Download\Documents\New"
For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" (Echo Directory
) Else If "%%~aZ" GEq "-" (Echo File) Else Echo Inaccessible
Pause
This is what I would like it to look like, but can't figure out:
@echo off
set "ATTR=%AppData%\Microsoft\Excel\XLSTART"
For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" GoTo DIR
Else If "%%~aZ" GEq "-" GoTo FILE
Else GoTo NOTFOUND
:DIR
Echo "Dir Found!"
Pause
:FILE
Echo "File Found!"
Pause
:NOTFOUND
Echo "NOTHING FOUND!"
Pause
回答1:
Taking the initial code in the link, and adding parentheses helps to break down the If
and Else
structure:
@Echo Off
For %%Z In ("%ATTR%") Do (
If "%%~aZ" GEq "d" (
Echo Directory
) Else (
If "%%~aZ" GEq "-" (
Echo File
) Else (
Echo Inaccessible
)
)
)
Pause
So to modify it with GoTo
's, perhaps something like this is more suitable for your purposes:
@Echo Off
PushD "%~dp0"
ClS
Set "ATTR=%AppData%\Microsoft\Excel\XLSTART"
For %%Z In ("%ATTR%") Do (
If "%%~aZ" GEq "d" (
GoTo DIR
) Else (
If "%%~aZ" GEq "-" (
GoTo FILE
) Else (
GoTo NOACCESS
)
)
)
GoTo NOTFOUND
:DIR
Echo "Directory Found!"
GoTo ENDFOR
:FILE
Echo "File Found!"
GoTo ENDFOR
:NOTFOUND
Echo "Not Found!"
GoTo ENDFOR
:NOACCESS
Echo "Inaccessible!"
:ENDFOR
Pause
Exit /B
回答2:
Fixed by putting the GoTo Foo
inside the brackets and making one line which I found easier to read since "ELSE" can't go on it's own line.
@echo off
pushd %~dp0
cls
::https://stackoverflow.com/questions/47954081/check-if-the-path-is-file-or-folder-using-batch
set "ATTR=%AppData%\Microsoft\Excel\XLSTART"
::For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" (Echo Directory
::) Else If "%%~aZ" GEq "-" (Echo File) Else Echo Inaccessible
::Pause
For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" (GoTo DIR) Else If "%%~aZ" GEq "-" (GoTo FILE) Else (GoTo NOTFOUND)
:DIR
Echo "Dir Found!"
Pause
GoTo ENDFOR
:FILE
Echo "File Found!"
Pause
GoTo ENDFOR
:NOTFOUND
Echo "NOTHING FOUND!"
Pause
GoTo ENDFOR
:ENDFOR
来源:https://stackoverflow.com/questions/56048421/break-batch-if-else-statement-into-multiple-lines-hard-to-read-code