Windows Batch Script Get Current Drive name

前端 未结 8 1779
情话喂你
情话喂你 2021-02-02 09:30

I have a batch file which is on a usb key. I need to know the drive name the batch is in.

Example, if it\'s E:\\mybatch.bat it should find E:\\ same thing for F:\\, G:\\

8条回答
  •  走了就别回头了
    2021-02-02 09:58

    Beware

    The existing answers to this question don't acknowledge that the question is actually asking about two different things:

    1. the drive of the current working directory (“Get Current Drive name”); and
    2. the drive of the batch file (“I need to know the drive name the batch is in”).

    These can be different when the batch file is started from a working directory other than its residing location. Readers should therefore be clear on the difference before determining which solution is relevant to their case.

    Drive of the current working directory

    %CD:~0,2%
    

    This takes the full current working directory and trims it down to the first two characters, which will be a drive letter and a colon, e.g. C:.

    Drive of the batch file itself

    %~d0
    

    This trims the full path of the batch file (in %0) to just a drive letter and a colon, e.g. C:.


    (this is an expanded version of my rejected edit to Kai K's answer)

提交回复
热议问题