Change Drive Letter

Description.

This script will check for a drive on a drive letter and if it finds a drive there it will move it the a new drive letter. This is great when you clone a computer that has a USB multi card reader which takes the top few drive letters and you have home drives mapped to one of those drive letters.

Source Code

Great script, works perfectly - exactly the kind of thing I was looking for - thanks

Did not work on Windows 2008 R2 SP1. It says “%%a was unexpected at this time.”

Ilkin, try saving this as a .bat and running it that way. This type error is normally because of a copy and paste, in which case the %%'s need to be change to single %'s. I just tested on 08r2 and it worked for me so let me know how it goes.

This is exactly what I was looking for. Many thanks!

Related Topics

Topic Replies Views Activity
Programming & Development 2 241 November 5, 2019
Programming & Development 7 422 September 1, 2017
Windows 5 169 January 26, 2012
Windows 8 110 June 30, 2014
Programming & Development 2 63 November 9, 2022

change drive letter batch

  • Links and bits
  • Sound Archive

Some words, pictures and sounds

  • April 13, 2010

Using current drive letter in batch script on a usb drive which changes drives letters

Following on from lasts week tip about Robocopy, if you are backing up to a USB drive there is a chance that every time you use the drive (maybe on different machines) under Windows you get a different drive letter.

So if you have a batch file saved on the drive with your finely crafted backup script, it may fail if your drive D:\ is now drive E:\

Enter to the rescue just the variable you need:

Which gives you the path to the file in which the script is being run from,

so something like

robocopy \\my-server\files %~d0\backupfolder /mir

saved as ‘backup.bat’ in the root of your usb drive will work everytime.

  • Author Info

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Phil Edmonds

Previous post

Robocopy your backup friend

The magic ipad effect.

' src=

Community Media practitioner based in Manchester. With over two decades of technical and production experience in low power FM and AM radio broadcasting, television, corporate video and internet development. A geek at heart I’m equally happy with a soldiering iron as building and programming computer systems, or finding my self on the roofs of tower blocks with antennas and dishes.

Posts by Phil Edmonds

change drive letter batch

Recommended Reading – 2023 Catchup

January 4, 2024

change drive letter batch

Recommended Reading – 2022 Catchup

June 1, 2023

change drive letter batch

Recommended Reading 2021 Catchup

April 6, 2023

change drive letter batch

Photo 365 Challenge (2021 – 351-365)

January 1, 2022

change drive letter batch

Photo 365 Challenge (2021 – 326-350)

December 17, 2021

Comments by Phil Edmonds

change drive letter batch

Digital Radio – Clearing the way for radio’s future

Dan, I will be putting up a link for people ...

change drive letter batch

Adobe Audition 3 (plus CS2) for free – too good to be true?

Some updates: Today, I tried logging into my Adobe account and ...

208 by me and the sysop

Bite a discount on your train station coffee

Update April 2012 - you now need to re-register for ...

Attempt to Save WordPress Post bug

Just as an addition to this - it appears that ...

Recent Flickr Pictures

#273of365 30th September 2016 On the air tonight

Recent Tweets

  • Photo 365 (27)
  • Sound Archive (38)
  • Uncategorized (4)
  • Computing (19)
  • Links and bits (58)
  • Podcast (3)
  • Website (4)

© 2009 - 2024 Phil Edmonds . Theme Design Anders Norén .

Change Directory - Select a Folder (and drive)

CHDIR is a synonym for CD.

Tab Completion

Tab completion allows changing the current folder by entering just part of the path and pressing TAB. C:> CD Prog [PRESS TAB] Will go to C:\Program Files\ Tab Completion is disabled by default, it has been known to create difficulty when using a batch script to process text files that contain TAB characters. Tab Completion is turned on by setting the registry value shown below: REGEDIT4 [HKEY_CURRENT_USER\Software\Microsoft\Command Processor] "CompletionChar"=dword:00000009

A Current Directory for each drive?

Originally in MS-DOS, each drive had its own current directory, for complex historical reasons . Now in Win32, there is one global current directory, but at the command line the appearance is still maintained that each drive has its own current directory, this is a fake-out by cmd.exe. The location for each drive is stored using the undocumented environment variables =A: , =B: , =C: etc. The only reason you need to be aware of this is that GUI Windows applications may have a different current directory than the command prompt. Similarly two CMD sessions can each have a different current directory.

Errorlevels

If the Current directory was changed: %ERRORLEVEL% = 0 If the Directory does not exist or is not accessible or if a bad switch given: %ERRORLEVEL% = 1

CHDIR is a synonym for CD

CD is an internal command.

Change to the parent directory:

C:\Work> CD ..

Change to the grant-parent directory:

C:\Work\backup\January> CD ..\..

Change to the ROOT directory:

C:\Work\backup\January> CD \

Display the current directory in the specified drive:

C:\> CD D:

Display the current drive and directory:

C:\Work> CD
C:\Work> ECHO "%CD%"

In a batch file to display the location of the batch script file (%0) :

C:\> ECHO "%~dp0"

In a batch file to CD to the location of the batch script file (%0):

C:\> CD /d "%~dp0"

Move down the folder tree with a full path reference to the ROOT folder:

C:\windows> CD \ windows\java C:\windows\java>

Move down the folder tree with a reference RELATIVE to the current folder:

C:\windows> CD java C:\windows\java>

Move up and down the folder tree in one command:

C:\windows\java> CD ..\system32 C:\windows\system32>

Change the Current Drive , Enter the drive letter followed by a colon:

C:> E: E:>

To change drive and directory at the same time:

C:> cd /D E:\utils E:\utils\>

If Command Extensions are enabled, which they are by default, the CD command is enhanced as follows:

The current directory string is not CASE sensitive. So CD C:\wiNdoWs will set the current directory to C:\Windows CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name that contains a space without surrounding the name with quotes. For example: cd \My folder is the same as: cd "\My folder" An asterisk can be used to complete a folder name: e.g. C:> CD pro* will move to C:\Program Files\

“Change is the law of life. And those who look only to the past or the present are certain to miss the future” ~ John F. Kennedy

Related commands

MD - Create Directory. pushd - Change Directory. RD - Delete directory or entire directory tree. How-to: Long filenames, NTFS and legal filename characters . Q156276 - Cmd does not support UNC names as the current directory. Equivalent PowerShell: Set-Location - Set the current working location. Equivalent bash command (Linux): cd - Change Directory.

How-To Geek

How to change a drive letter on windows 10 or windows 11.

4

Your changes have been saved

Email Is sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

T-Mobile Home Internet Reverses Its Recent Price Increase

Proton pass now has secure login sharing, thunderbird's big "nebula" update is now available, quick links, what changing a drive letter does, how to change a drive letter, how to fix programs broken by changing a drive letter.

Changing the letter of a drive is easy on Windows 10 and Windows 11, but you should do it as soon as you add the drive to prevent future hassles. Find out how to change a drive letter here.

Windows assigns drive letters alphabetically --- starting with C --- when they're initialized. If you want to change a drive letter, you should do it before you install anything on the drive. Changing a drive letter after programs are installed could break them since there will be references to an installation location that is no longer there.

Windows has gotten pretty smart about updating shortcuts so that programs work after changing a drive letter. Most of your applications' shortcuts will probably be automatically corrected. Unfortunately, Windows isn't as good about updating file associations. You'll have to manually set the default apps associated with files to fix file associations if they were broken by changing the drive letter.

It is possible to change the boot drive letter to something else, but we don't recommend it. Changing C:\ to another letter is likely to result in severe issues, like a PC that cannot boot into Windows at all. Even if it were able to boot, there would be a huge number of programs that would not be able to run.

Technically speaking, while they are commonly called drive letters, each letter actually refers to a partition on a disk. If you have multiple partitions on a single disk, you will need to assign a letter to each partition to make them all accessible. If a disk has just a single partition, it will just have a single letter pointing to that partition. (However, you do not have to assign a letter to each partition. Partitions without drive letters will not appear in File Explorer and elsewhere.)

Changing a drive letter is pretty simple. Click the Start button, type "Disk Management" in the search bar, and then hit Enter.

The program name displayed in the search will not be Disk Management. It will be "Create and format hard disk partitions."

Start menu search showing disk manager result is not called disk manager

You could also hit Windows+X or right-click the Start button, and then click "Disk Management."

Click "Disk Management."

Identify the drive you'd like to change in the Disk Management Window. In this example, we'll change the letter of the D:\ drive to J:\. You can right-click the drive on the text list, or on the menu below. Either works.

Right click the drive in the list, or right click the drive on the menu at the bottom.

Select "Change Drive Letter and Paths" in the right-click menu that appears.

Click "Change Drive Letter and Paths."

In the window that pops up, click "Change."

Click "Change."

Select whatever letter you want from the drop-down menu. Then click "Ok."

Select letter from drop down menu, then click "Ok."

Two popups will warn you about changing your drive letter. Click "Yes" on both of them, and then restart your computer.

Once Windows has restarted, the drive letter should be changed.

Arrow pointing to change drive letter.

There are a few ways you can fix a program broken by changing the drive letter.

Fix The Shortcut

If you're lucky, the only thing that is broken is the shortcut. Fix a shortcut by right-clicking the shortcut on your desktop, and then click Properties.

Click "Properties."

You need to change the target of the shortcut to the new drive letter.

For example, if GIMP was previously installed at " D :\GIMP 2\bin\gimp-2.10.exe," and you changed the D drive to J, change the target of the shortcut to " J :\GIMP 2\bin\gimp-2.10.exe."

Finalize the change by clicking "Apply" and then "Ok."

Edit the shortcut. Then click "Apply" and "Ok."

Reinstall the Program

Reinstalling the program will generate new entries in the registry, so everything on the computer will know where to look for the program. Some installers won't like reinstalling directly over existing files, so you may need to rename or delete the old installation first.

Change the Drive Letter Back

If you changed the drive letter of a drive with a lot of programs installed, it might be easier to change the drive letter back. Changing the drive letter back should automatically fix any programs and file associations that were broken.

Edit the Registry

You can break programs, or even Windows itself, by editing the registry. Be careful, and learn about how to edit the registry before you try it. Make sure you backup the Windows registry first. You should not attempt this method unless you have no other options.

Windows, and a lot of programs, track where programs are installed via the Windows registry. It is possible to manually adjust the registry to fix broken programs. Keep in mind that there could be dozens of registry entries you need to edit. A program like GIMP can have registry entries for the context menu, for the "Open With" menu, for any file associations, and for the location of its executables. Other programs may only have a few entries related to where it is installed.

If you're not deterred, here's how you do it.

First, you need to know where the program was previously installed. In this case, the program was installed to the "D:\GIMP 2" folder, and the executables were found the "D:\GIMP 2\bin" sub-folder. It is now located at "J:\GIMP 2" instead.

We need to update the registry to reflect the change in location. Click the Start button, type "regedit" into the search bar, right-click Regedit, and click "Run as administrator."

Click "Run as administrator."

In Regedit, hit Ctrl+F to bring up a search window. Type in the old location for the program you're trying to fix --- "D:\GIMP 2" for our example --- then click "Find Next."

Click "Find next."

Once Regedit has found something with "D:\GIMP 2" as part of a path, it'll show it to you. Here is an example from the GIMP search.

Some of the GIMP search results found in the registry.

To actually change them, double click the name of the registry entry you want to modify. Then change the drive letter to J, or whatever you chose. If you didn't otherwise move the folder, leave the rest of the path alone. Then click "Ok."

Change the drive letter in Value Data.

You'll need to repeat this multiple times. To find the next result using your search term, you can hit the F3 key. There will be a popup once you've found all of the entries.

Changing drive letters can be a simple way to customize your PC. Do it before you install anything on the drive, however. You'll prevent any problems before they occur, and probably save yourself quite a bit of troubleshooting.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How to get a list of drive letters on a system through a windows shell (bat, cmd)?

How do I get a list of drive letters and their associated labels on a windows system through a bat file?

  • windows-command-prompt

Eduardo Ivanec's user avatar

14 Answers 14

This will get most of it:

If you have any drives mapped via subst you would also need to get those:

For completeness, you would do it like this in Powershell (if you are on windows 7 or have installed it):

You can also do it from the command prompt or a batch file using WMI like this:

Dennis Williamson's user avatar

  • 1 This doesn't list local disk drives like any internal hard drives or cdroms. Am I missing something? –  Chris Magnuson Commented Sep 4, 2009 at 21:12
  • Nope, I misunderstood the question. I thought that you only wanted mapped drives. I will edit. –  EBGreen Commented Sep 4, 2009 at 21:18
  • 2 The wmic solution should give you everything. –  EBGreen Commented Sep 4, 2009 at 21:20
  • You need to remove the quotes from wmic logicaldisk get "caption,providername,drivetype" so that it is wmic logicaldisk get caption,providername,drivetype other wise it throws an error. EBGreen you have single handedly blown my mind for the day, I have never seen wmic even though I have been scripting various server builds for weeks and I am extremely excited to see what else I can do with it. Great job! –  Chris Magnuson Commented Sep 4, 2009 at 21:24
  • 1 wmic logicaldisk get caption,providername,drivetype,volumename the VolumeName was what I was missing, if you update yours with that I will accept it as the answer. Thanks –  Chris Magnuson Commented Sep 4, 2009 at 21:31

To use diskpart, there is no need to create an intermediate file. Try:

gnoise's user avatar

  • 2 This is the best answer and returns the most info about the mounted drives in a beautiful format. –  ekerner Commented May 29, 2013 at 7:41
  • 1 but it requires admin rights –  LogicDaemon Commented Mar 1, 2017 at 7:56

Fast, flexible and efficient. Although a little complex.

Dharma Leonardi's user avatar

  • I don't know what versions of Windows this works on but I just tested it on my Win 7 and XP machines and got the following output from both: ` DRIVE LETTER(s):USED: " =" DRIVE LETTER(s):FREE: "!TMP_FREE_DRIVE_LETTERS!"` –  John Gardeniers Commented May 12, 2011 at 0:44
  • Sorry, you need to put this in the beginning of the batch file. setlocal enabledelayedexpansion –  Dharma Leonardi Commented May 12, 2011 at 3:19
  • I've edited your answer to include the missing line. It works now. +1 –  John Gardeniers Commented May 12, 2011 at 3:31

inspired by Scott

also shows CD drive letters and network mounted disk letters. No need to have admin rights.

Geoleven's user avatar

  • simple and works –  Tyler Liu Commented Feb 27, 2013 at 10:13
  • "i was unexpected at this time." –  Berit Larsen Commented Sep 7, 2015 at 9:05
  • @BeritLarsen you need to double up % symbols if running it as a batch file rather than on the command line. –  TessellatingHeckler Commented Oct 26, 2016 at 0:02

If anyone is lucky enough to be using Vista (Vista Ultimate SP2 b6002, in my case) and the gwmi and wmic snippets given here don't work exactly, here is what I did to make it work.

For gwmi , if you receive no output, try changing the DriveType to 3. If still having problems, remove the -filter option altogether and analyze output.

For wmic , if you receive "Invalid GET Expression", then try putting the get expression in quotes:

tdowg1's user avatar

sample output

Jader Dias's user avatar

This site has a much simpler set of calls:

http://en.code-bude.net/2013/02/23/show-all-drives-in-command-prompt/

Show local drives:

wmic logicaldisk get deviceid, volumename, description

If you want to show only drives of a particular type, the wmic command can be further expanded to include a where clause.

wmic logicaldisk where drivetype=2 get deviceid, volumename, description

0 => Unknown

1 => No Root Directory

2 => Removable Disk

3 => Local Disk

4 => Network Drive

5 => Compact Disc

6 => RAM Disk

David Tr's user avatar

  • I tried this one and it didn't work. I think there needs to be a space in front of the /s but even with that change it didn't work. I put the above in a file, d.bat and I see the diskpart window flash up but then disappear and the cmd shell where I'm running this then shows the pause running. –  slm Commented Dec 21, 2011 at 3:27

I found the diskpart approach reports DVD drives with no disc inserted, and doesn't report SD cards with valid drive volumes

jscott's user avatar

  • does not work for windows xp –  Tyler Liu Commented Feb 27, 2013 at 10:15

pbies's user avatar

Somewhat kludgy, but works from a batch file:

Nexus's user avatar

Although it has enough answer, I'd like to add one when you want to use it in batch file. If you get "Invalid GET Expression", you could put a ^ before the ',', like below:

Mingjiang Shi's user avatar

  • What does this ^ do here? –  vonbrand Commented Mar 27, 2013 at 10:10
  • It is cmd.exe's escape character, similar to \ in Unix like shells. –  gimpf Commented May 12, 2013 at 11:39

Using wmic in a for loop to determine all the available drives.

There is also this little hack using exit codes 65 to 90 converted to ascii which will return all Alpabetical characters A to Z with all credit to Aacini.

Gerhard's user avatar

  • Um, wow. So if you can distill that into something that would actually just output the drive letters and labels that exist on the system that would be closer to the answer to the question though this is it least movement in the right direction. –  Chris Magnuson Commented Sep 4, 2009 at 21:16
  • I'm getting down-voted for providing a solution that meets the criteria? Wow... –  Scott Commented Sep 5, 2009 at 5:19
  • 4 Well, for one thing, it produces errors for drives that exist but contain no media, such as a CD/DVD drive. –  Dennis Williamson Commented Sep 6, 2009 at 12:47

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows batch-file windows-command-prompt ..

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • We spent a sprint addressing your requests — here’s how it went

Hot Network Questions

  • Why does ansible reevaluate a variable on each access
  • How does the Sega Master System handle a sprite moving off the left edge of the screen?
  • How should I analyse TV episode popularity while accounting for time?
  • how to say the adjectival "one-time" / "non-recurrent" in Latin
  • how to round numbers after comma everytime up
  • LuaLaTeX: change font id does not work with a non default font
  • What is the next layers of defence against cookie stealing if GET parameter is vulnerable to XSS and there is no HttpOnly flag in a website?
  • I feel guilty about past behavior in my college
  • Can my necromancer have this bridge built with those constraints?
  • What's the grammatical structure after a comma?
  • Default QGIS style symbologies not displaying
  • What is more important: simplicity or induction?
  • Questions about writing a Linear Algebra textbook, with Earth Science applications
  • Membership and offices in the Privy Council – what is the significance of the different predicates used to describe the transactions?
  • Can a star be made of sun spots?
  • Has a rocket engine ever been reused by a second/third stage
  • Trouble understanding the classic approximation of a black body as a hole on a cavity
  • 6/8 or 2/4 with triplets?
  • How does light beyond the visible spectrum relate to color theory?
  • How do we we scan 'nunc tantum sinus et statio mala fidèle carinis'
  • A Ring of Cubes
  • Tax Implications of exercising both NSOs and ISOs
  • The use of Bio-weapons as a deterrent?
  • Why does FindInstance[x>0,x] give 27?

change drive letter batch

MiniTool

How to Change Drive Letter with CMD Windows 10

Diskpart is a command-line tool in Windows system that allows you to manage your disks and partitions. This post introduces how to change drive letter with CMD in Windows 10, namely, by using Diskpart CMD tool. MiniTool software provides users a free disk partition manager, data recovery software, system backup and restore software, etc.

If you want, you can change drive letter for a drive with CMD (Command Prompt) in Windows 10. This post includes detailed guides for how to use Diskpart command-line tool to change driver letter in CMD.

How to Change Drive Letter with CMD in Windows 10

Diskpart is a Windows built-in CMD tool that lets you easily manage hard drive and change drive letter. To change or assign drive letter in CMD, you can firstly open Diskpart utility in Command Prompt. Check the steps below.

Step 1. Open CMD in Windows 10

You can press Windows + R , type cmd , and press Ctrl + Shift + Enter to open elevated Command Prompt .

Step 2. Open Diskpart tool

In Command Prompt window, you can type diskpart command, and press Enter . This will open the Diskpart command-line utility.

Step 3. Change drive letter CMD

Next you can type the command line below to change drive letter in Command Prompt in Windows 10. Remember to press Enter after typing each command line.

  • list volume (this command will list all available volumes detected by your computer)
  • select volume * (replace “*” with the exact volume number of the target partition)
  • assign letter=* (replace “*” with the preferred drive letter like “F”)

Windows change drive letter

After you change or assign a drive letter for a drive or device, Windows will display the same letter automatically next time you reconnect the device to your computer.

If you want to remove the drive letter of a specific drive, you can type remove letter=* command and press Enter . Still, replace “*” with the exact drive letter of the target drive.

How to Change Drive Letter Using PowerShell

Some Windows 10 users might find that Command Prompt is missing from Win + X menu , and instead, it shows Windows PowerShell. Windows PowerShell can do most things that Command Prompt does. Alternatively, you can also use Windows PowerShell to change drive letter in Windows 10.

Step 1. Press Windows + X , and choose Windows PowerShell (Admin) to run Windows PowerShell utility as administrator.

Step 2. Next type get-disk command and press Enter to list all available drives the computer detected.

Step 3. Then you can type the command: Get-Partition -DiskNumber 1 | Set-Partition -NewDriveLetter F , and press Enter to assign a new drive letter. You should change “*” with the actual disk number of target drive, and replace “F” with the new drive letter you’d like to assign to the drive.

change drive letter PowerShell

MiniTool Partition Wizard – Professional Free Disk Partition Manager

Instead of using CMD or PowerShell to change drive letter for a drive in Windows 10, you can also utilize third-party free disk partition manager like MiniTool Partition Wizard to easily change drive letter and manage disk partitions on Windows 10.

MiniTool Partition Wizard let you easily create/delete/extend/resize/format/wipe partitions, convert partitions formats, migrate OS, clone disk, test hard drive speed , analyze hard drive space usage, check and fix disk errors , and more.

change drive letter with MiniTool Partition Wizard

By following the detailed guides above, you can easily change drive letter with CMD (Command Prompt), PowerShell or MiniTool Partitioon Wizard on Windows 10.

About The Author

Position: Columnist

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Change a drive letter from Command Prompt or batch script in Windows 8?

I have an external hard drive that I connect often to my computer. At some point it was assigned letter G: and based on that my other software works.

Nowadays, suddenly it gets letter F:

Is there any way I can use a batch script to change the letter from F: to G:. I don't mind running the batch script manually?

If so, what is the code I should use and will it need administrative permissions?

  • command-line

gontadu's user avatar

  • 1 See diskpart and yes you need admin. In theory it should have remembered the drive letter, consider changing it manually on disk management first. –  Bob Commented Jul 28, 2013 at 18:31
  • @Bob: It could be that it only remembers drive letters after they have been assigned manually at least once. –  grawity_u1686 Commented Jul 28, 2013 at 19:57
  • 1 Thanks! I have changed it a couple of times manually, but everytime it goes back to the old one. –  gontadu Commented Aug 6, 2013 at 14:42
  • I have noticed that it was remembered when I had one device using a drive letter. When I started using multiple devices with the same drive letter, they get forgot, I have not verified the hypothesis, but I guess Windows 10 remembers the last device assigned to a drive letter. –  BtF Commented Aug 2, 2021 at 8:56

There are several methods:

mountvol – use it once to delete an existing letter, then again to assign a new one;

diskpart – interactive;

diskmgmt.msc aka Disk Management – a graphical tool.

Whichever you choose, assigning once should be enough, the assignment will be remembered afterwards.

grawity_u1686's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows windows-8 command-line batch ..

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process

Hot Network Questions

  • Can a star be made of sun spots?
  • Upper Midwest weed - how to prevent/kill?
  • Is removing the frightened condition the same as making a successful saving throw when it comes to immunity from the effect?
  • What does impedance seen from input/output mean?
  • Keeping US Citizenship While Living Abroad (Japan)
  • Ideas for an alternative to nuclear weapons as a deterrent?
  • Does (and how?) darkvision work underwater?
  • Mechanism behind a pink human skeleton
  • What is the next layers of defence against cookie stealing if GET parameter is vulnerable to XSS and there is no HttpOnly flag in a website?
  • What's the price of banana?
  • How much should we generally trust security-only support of a legacy version of a software and what should we look out for?
  • Is the "ぐらい" always needed in "どのぐらいかかりますか?"
  • Question on special relativity
  • How does light beyond the visible spectrum relate to color theory?
  • How can I fix this rust on spokes?
  • How does the Sega Master System handle a sprite moving off the left edge of the screen?
  • Why were early (personal) computer connectors so bulky?
  • How would the dynamics of discourse change if your interlocutor were a superintelligent being?
  • How did Sirius Black bring the Weasley family picture back from Azkaban?
  • In the travel industry, why is the "business" term coined in for luxury or premium services?
  • Tax Implications of exercising both NSOs and ISOs
  • Is there a minimal (least?) countably saturated real-closed field?
  • Linux disk space running full
  • I feel guilty about past behavior in my college

change drive letter batch

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Find USB Drive letter

I need to get the drive letter of the usb pen drive.the command CHDIR >drive.txt gives me the drive letter L:.How do I read/get this info "L:" without quotes into a variable in my batch file

5 Answers 5

Here's how to get a USB drive letter from any drive.

sparky3489's user avatar

  • this is useful; but what if there is a (multi) card reader it will mention them too. –  M. A. Commented Mar 28, 2015 at 9:27

Whatever chdir outputs can also be used by the pseudo-variable %CD% . So you already have a variable with that information.

Otherwise you can use for :

But I think %CD% is much easier :-)

EDIT: You said that with the quotes already. You won't have any quotes in the variable unless you want them in there.

As for the trailing backslash: You can use the following instead of %CD% :

which will expand %CD% and remove the last character, which you know is the backslash.

Still, will only work if you're in the root directory of that drive. Otherwise you can also use

Joey's user avatar

  • %CD% is ok similar to chdir but I need to remove the backslash "\" the variable should only be "L:" without quotes –  Dario Dias Commented Apr 25, 2009 at 10:34

Using, in your batch, something like:

Would yeld a content of L: as you asked, if this is the current directory the script is in, at the point when you use it. If you have some popd/pushd, cd, etc.. within the batch, take care when you use it. The rest is up to you

Providing how you would use it (a part of your batch maybe) would have help alot to receive a better answer. We only can guess. The reason, I think, for the couple of for loops in answers. Might not be needed but we're guessing.

Jay's user avatar

This i what i use to find the letter on my USB

  • Just change the "NAME OF THE USB" to the name of the USB

Torbjörn Dahlgren's user avatar

Since cd will output something like:

you need to just grab the first field using "\" as the delimiter as follows:

This will set the environment variable curdrv to c: for the aforementioned output.

Don't forget to use the double-% (%%d) variant if running inside a cmd file.

paxdiablo's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • How can I explain the difference in accuracies in different ML models?
  • What is the light mentioned in the beginning of the book of Genesis
  • Gloomy anime about suicidal athletes
  • Is the "ぐらい" always needed in "どのぐらいかかりますか?"
  • Has a rocket engine ever been reused by a second/third stage
  • Question on special relativity
  • Does the oven temperature for a lasagna really matter?
  • Can Curve25519 shared secret be safely truncated to half its size?
  • How does anyone know for sure who the Prime Minister is?
  • How can I get rid of/ smooth out weird/ sharp edges like this?
  • How can I fix this rust on spokes?
  • Guarantor for 60-day Indonesia C1 tourism visa?
  • Forgot to pay Gatwick Dropoff Charge
  • Two isotropic subspaces in a symplectic vector space
  • Excel in both teaching and research as a junior faculty member
  • 6/8 or 2/4 with triplets?
  • What side-effects, if any, are okay when importing a python module?
  • Continued calibration of atomic clocks
  • Why does FindInstance[x>0,x] give 27?
  • Calculate sum of self-exponentation
  • how to round numbers after comma everytime up
  • Cost sharing application in Python
  • Issues with ICL7660 ICs from eBay - Overheating and Failure
  • ミラさん が すんで いた うち を かいました。who brought the house? Me or mira san?

change drive letter batch

IMAGES

  1. Quick Guide: Changing Drive Letters in Windows 10

    change drive letter batch

  2. How to Change Drive Letter in Windows 10 (Easy to Follow Guide)

    change drive letter batch

  3. How to Change Drive Letter in Windows 10

    change drive letter batch

  4. Windows 10 change drive letters

    change drive letter batch

  5. How to Change Drive Letter with CMD Windows 10

    change drive letter batch

  6. How to change the drive letter in Windows 10/11, DVD and USB drives?

    change drive letter batch

VIDEO

  1. How to Change Drive Letter in Windows 11/10

  2. How to Change Drive Letter of HDD and SSD

  3. How to Change Drive Letter in Windows 11/10 [Easiest Way]

  4. Change Drive Letter to Hide Partition.mp4

  5. How to Change Drive Letter in Windows 11?

  6. The letter that changed everything! 💌 #shorts #shortsfeed #ytshorts

COMMENTS

  1. windows

    If you run the .BAT file from the USB drive you don't need to specify the drive letter, only the path and/or file relative to the .BAT file. Example: If Unzip.BAT is in the root of the USB Drive and the .zip is in a folder called "classified docs" under a folder called "secret" it would be \secret\classified docs\

  2. batch file to remove and reassign drive letters

    Drive 2 : X. Then after a set amount of time for the software to boot and load the drive, swap the letters. Drive 1 : X. Drive 2 : Y. To do this I was looking into using a diskpart script, but can't seem to get it to work through a batch file. volume 0 remove drive letter. volume 1 remove drive letter // this way they are both blank so I don't ...

  3. How to change directory to run .bat files from different drive?

    I have some .bat files that I run from the local directory (e.g. C:\Users\pozna001). However, when I try and change the directory to a data drive using cd F:\nrcs_project to run the .bat files from a different location, I see that the command prompt does not recognize the cd command. How can I change the directory in the command prompt so that I can run these .bat files from a different drive ...

  4. Using a .BAT file to change a USB drive-letter

    It is possible using diskpart. Open Command Prompt. Type: " diskpart ". At the DISKPART prompt, type: " list volume " and make note of the number of the simple volume whose drive letter you want to assign, change, or remove. At the DISKPART prompt, type: " select volume n " Select the volume, where " n " is the volume's number, whose drive ...

  5. batch file

    In case of the batch file is stored on the USB drive and executed from there with a double click, use xcopy "\directory" "c:\directory" /s /y because a path starting with a backslash is relative to root of current drive or use xcopy "%~d0\directory" "c:\directory" /s /y because %~d0 references the drive (letter plus colon) of first argument ...

  6. Batch file help with changing drive letter

    Hello all, I'm writing a batch file that will deploy a gold image to machines from a flash drive. I want the script to set a default letter(T) for the flash drive(so that no matter the machine type the drive letter will work), then change to the letter and run the rest of the script, but once I get out of diskpart, the script terminates and fails to both change to the new drive and continue ...

  7. Manually assigning a drive letter using CMD/Diskpart

    Procedure. Open up a command prompt (CMD/PowerShell). Type "diskpart" to start up diskpart. You will see the prompt change to "DISKPART>". Type "list vol" to list all available volumes. You can identify the drive by size and file system. Additionally, the volume doesn't currently have a drive letter. Select the volume using "sel vol <number>".

  8. Change Directory in Windows Batch Script

    Change to Drive Letter. To change to a specific drive letter while the command prompt directory is using a different drive letter than the one you need to change to, simply use the /D parameter with the CD command (e.g. CD /D <DriveLetter>:) to change to a different drive letter before running proceeding commands.

  9. Change Drive Letter

    Description This script will check for a drive on a drive letter and if it finds a drive there it will move it the a new drive letter. This is great when you clone a computer that has a USB multi card reader which takes the top few drive letters and you have home drives mapped to one of those drive letters. Source Code @echo off cls title "Changing device drive letters..." set ChangeNeeded ...

  10. Using current drive letter in batch script on a usb drive which changes

    Using current drive letter in batch script on a usb drive which changes drives letters. Following on from lasts week tip about Robocopy, if you are backing up to a USB drive there is a chance that every time you use the drive (maybe on different machines) under Windows you get a different drive letter.

  11. CD Change Directory

    Change the Current Drive, Enter the drive letter followed by a colon: C:> E: E:>. To change drive and directory at the same time: C:> cd /D E:\utils E:\utils\>. If Command Extensions are enabled, which they are by default, the CD command is enhanced as follows: The current directory string is not CASE sensitive.

  12. How to Change a Drive Letter on Windows 10 or Windows 11

    Changing a drive letter is pretty simple. Click the Start button, type "Disk Management" in the search bar, and then hit Enter. The program name displayed in the search will not be Disk Management. It will be "Create and format hard disk partitions." You could also hit Windows+X or right-click the Start button, and then click "Disk Management."

  13. Batch scripting: iterate over drive letters?

    set /a iter=!iter!+1. REM the pos variable is the position in the string of drive letters that needs to be taken out for this iteration. set /a pos=!iter!-1. REM this sets the driveX variable where X is the drives correlated number to the letter of that drive from the long string of drive letters by using the pos variable.

  14. Drive letter of given file in windows batch

    I want to get the Drive letter of the file. Example: myScript.bat C:\exampleFolder\somefile.txt D:\someOtherFolder\differentfile.txt ... %~s1 Change the meaning of f, n, s and x to reference the Short 8.3 name (if it exists.) ... parameters - A command line argument (or parameter) is any value passed into a batch script. Share. Improve this answer.

  15. batch file

    If anyone is lucky enough to be using Vista (Vista Ultimate SP2 b6002, in my case) and the gwmi and wmic snippets given here don't work exactly, here is what I did to make it work.. For gwmi, if you receive no output, try changing the DriveType to 3.If still having problems, remove the -filter option altogether and analyze output. gwmi win32_LogicalDisk -filter DriveType=3

  16. How to Change Drive Letter with CMD Windows 10

    Open CMD in Windows 10. You can press Windows + R, type cmd, and press Ctrl + Shift + Enter to open elevated Command Prompt. Step 2. Open Diskpart tool. In Command Prompt window, you can type diskpart command, and press Enter. This will open the Diskpart command-line utility. Step 3. Change drive letter CMD. Next you can type the command line ...

  17. batch

    There you can change the drive letter that's assigned to the drive. After this is done, whenever the drive is plugged back in, ... Create your batch file scripts using %~d0 as the drive letter and colon. %~d0 is replaced by the drive containing the script. So if on one machine the thumb drive is F %~d0 is equivalent to F: On another machine the ...

  18. Statement on the Approval of Spot Bitcoin Exchange-Traded Products

    Today, the Commission approved the listing and trading of a number of spot bitcoin exchange-traded product (ETP) shares. I have often said that the Commission acts within the law and how the courts interpret the law.

  19. Change a drive letter from Command Prompt or batch script in Windows 8

    3. There are several methods: mountvol - use it once to delete an existing letter, then again to assign a new one; diskpart - interactive; diskmgmt.msc aka Disk Management - a graphical tool. Whichever you choose, assigning once should be enough, the assignment will be remembered afterwards. Share.

  20. batch file

    I need to get the drive letter of the usb pen drive.the command CHDIR >drive.txt gives me the drive letter L:.How do I read/get this info "L:" without quotes into a variable in my batch file ... Resolve usb drive letter in batch file on any host computer. 2. ... Batch file to find USB drive and change drive letter. 2.