• 0

[MS-DOS Batch] Automatically determine if drive is already mapped


Question

I didn't know if I should start this topic under "Programming" but it seems to be the only place to put it.

I want to run a batch file that will automatically map a network drive before it continues the script. The problem I have is that if for some reason the drive is already mapped, or the batch file has been run twice in one session, the "net use" command returns an error. The script still works in the end, but I would like to bypass the "net use" command altogether if the drive is already mapped.

I've been digging through the net trying to find anything that can help me out, but to no avail. The closest thing I can find is just typing "net use" can tell you if the drive is already mapped or not, but I can't take any one piece of that result and use it in my script.

Does anyone have any suggestions? My purpose here is to write an IF statement that determines:

IF drive X: is already mapped, then skip net use command and proceed with the remainder of the script.

ELSE, run net use command and proceed with the remainder of the script.

I figured ERRORLEVEL could come in handy, but that only works after I get the error that I'm trying to avoid in the first place.

Thanks!

19 answers to this question

Recommended Posts

  • 0

I would be careful with what you are checking. If the user mapped a different drive than the one that is supposed to be there, it may see a drive mapped and skip the mapping.

What we have done is unmap and then map the drive in the same script. This will ensure that the correct drives are mapped to the desired letter every time.

  • 0

You could always look for a specific file to that share, which should eliminate the chance of having the wrong share mapped.

Unmapping the share could cause issues if other processes are using the same share.

  • 0
  t_r_nelson said:
I would be careful with what you are checking. If the user mapped a different drive than the one that is supposed to be there, it may see a drive mapped and skip the mapping.

What we have done is unmap and then map the drive in the same script. This will ensure that the correct drives are mapped to the desired letter every time.

Very true. I thought about that but I realized that this is happening in a fairly controlled environment... but I suppose it would be good to do. The only downside is if I try to unmap it while another resource is using the same drive to do something, causing other errors in the process.

  Joe USer said:
How about using IF EXIST for a file on the mapped drive?

Asssuming W: is your mapped drive.

IF NOT EXIST W:\. netuse..etc..

I might give that a try, thanks. I suppose maybe I can merge these two suggestions together? To unmap a drive you have to make sure the drive is mapped in the first place otherwise another error will appear. *sigh*

Also, thanks for your speedy replies.

EDIT:

  Joe USer said:
You could always look for a specific file to that share, which should eliminate the chance of having the wrong share mapped.

Unmapping the share could cause issues if other processes are using the same share.

Yes exactly. If I look for a specific file on that share, I wouldn't need to unmap at all.

I'll give that a try now and report back.

  • 0

I made an assumption that mappings are needed, can you run the process using UNC without having to map to a specific drive letter?

  t_r_nelson said:
Good point, Joe. I was just considering the case of the script running at login.

I learned that the hard way, with WFW 3.11.

Multithreaded batch processing, completely crazy, but it worked.

  • 0

Alright I just gave this a try and it seems to work perfectly fine so far. I'll keep testing to make sure.

@echo off

echo --------------------------------------------------

echo Now running database maintenance. Please wait...

echo IMPORTANT: DO NOT TOUCH THE COMPUTER DURING THIS PROCESS

echo --------------------------------------------------

IF EXIST \\domain and filename here.exe (

echo The drive is already mapped.

GOTO SKIPPED

) ELSE (

echo The drive has not yet been mapped.

net use x: \\domain and share here Password /user:domain\user

)

:SKIPPED

[command that I need to run regardless]

echo --------------------------------------------------

echo Maintenance complete.

echo --------------------------------------------------

pause

Thanks for the help guys! I'll post here again if something comes up. The only thing I'm uncertain about is if it's okay that I don't specify X: in the EXISTS statement.

  • 0
  jake1eye said:
Here is a link to a HTA from the Hey Scripting Guys that uses a HTA to list available drive letters and how to map that drive.

Hey Scripting Guys

Thanks, but that seems to be for VBScript. I'm just working with command line batch.

  • 0
  Xtreme $niper said:
Alright I just gave this a try and it seems to work perfectly fine so far. I'll keep testing to make sure.

@echo off

echo --------------------------------------------------

echo Now running database maintenance. Please wait...

echo IMPORTANT: DO NOT TOUCH THE COMPUTER DURING THIS PROCESS

echo --------------------------------------------------

IF EXIST \\domain and filename here.exe (

echo The drive is already mapped.

GOTO SKIPPED

) ELSE (

echo The drive has not yet been mapped.

net use x: \\domain and share here Password /user:domain\user

)

:SKIPPED

[command that I need to run regardless]

echo --------------------------------------------------

echo Maintenance complete.

echo --------------------------------------------------

pause

Thanks for the help guys! I'll post here again if something comes up. The only thing I'm uncertain about is if it's okay that I don't specify X: in the EXISTS statement.

IF EXIST \\domain and filename here.exe (

Once you use a UNC connection you're going to be logged into the server as the current user. If the users are different, then you're going to have a problem. You should specify the X: in the if exists.

  • 0

Hmm alright, so then should I do:

IF EXIST X:\\address\file.exe

or

IF EXIST X:\file.exe ?

For some reason I'm tempted to use the second one but the first one seems more technically correct to me...

  • 0
  Xtreme $niper said:
Hmm alright, so then should I do:

IF EXIST X:\\address\file.exe

or

IF EXIST X:\file.exe ?

For some reason I'm tempted to use the second one but the first one seems more technically correct to me...

X:\file.exe is what you want, (assuming it's in the root of the share)

  • 0

Alright I thought so (yes it's at the root). Thanks.

But now I have another problem. I want to schedule this using the "Schedule Task" app on WinXP. The only problem is the computers here are required to press CTRL+ALT+DEL before you can log in (secure logon). For some reason the batch script fails to do any mapping when it is run at the "press CTRL+ALT+DEL to log in" screen.

However, if I do press CTRL+ALT+DEL and go to the actual log in screen (still not logged in) the script works fine. Any ideas why, or how to get around this?

EDIT: I ran into this idea here, http://joedix.com/tech_help/2006/07/schedu...running-wo.html but I think that would be a pretty big security risk, no?

Edited by Xtreme $niper
  • 0
  Xtreme $niper said:
Alright I thought so (yes it's at the root). Thanks.

But now I have another problem. I want to schedule this using the "Schedule Task" app on WinXP. The only problem is the computers here are required to press CTRL+ALT+DEL before you can log in (secure logon). For some reason the batch script fails to do any mapping when it is run at the "press CTRL+ALT+DEL to log in" screen.

However, if I do press CTRL+ALT+DEL and go to the actual log in screen (still not logged in) the script works fine. Any ideas why, or how to get around this?

EDIT: I ran into this idea here, http://joedix.com/tech_help/2006/07/schedu...running-wo.html but I think that would be a pretty big security risk, no?

What account are you running the task under? Does it have a password?

  • 0

I'd be running this task under non-administrator accounts I believe. All accounts have to have a password, and every user has to press the CTRL+ALT+DEL combo before logging in.

I'm not sure why but it seems drive mapping doesn't work if you don't press CTRL+ALT+DEL.

EDIT: I just did another round of testing. The drive mapping actually doesn't work in ANY form if your account is locked. I previously thought as long as you hit the safe logon combo first you'd be okay, but apparently I was wrong.

As long as the system is at the login screen (even though the account itself is logged in) the application that needs to be run from the network share won't run, causing the script to fail.

Any ideas?

Edited by Xtreme $niper
  • 0

Ok, that's a little strange, I run batches via the task shceduler in Windows 2000 all the time.

Are you on a domain? What OS/SP are you using (XP sp2?)?

Have you tried using an admin account?

Are you using the task scheduler or the AT command?

Also, try this, get a copy of whoami.exe from the MS resource kit and pipe the output to a local file, see if it's using the correct account.

  • 0

Well I guess it's more complicated than just that... I forgot to mention I'm using an application called TestPlanner that automates some tasks for you by controlling the keyboard and mouse to accomplish "macro" like tasks.

The script itself actually opens and runs, but the problem is once the TestPlanner app runs, it's supposed to do a few things. One of which is to open the run window from the start menu and run another application... but for some reason the keys are never mapped to the text field within the run window and so the script fails.

So now I realize your ability to help me out can easily end here, because you probably have no idea what this TestPlanner application is...

The problem is that I am just an employee in a corporation, so there is no chance of me getting admin access. I don't think that's the problem though. I think that because the computer is in a locked state, the text field in the run command window can't be selected and so the script fails when it is trying to enter text into a field that cannot be selected. It looks like I just can't get a fix for that.

  • 0
  Xtreme $niper said:
Well I guess it's more complicated than just that... I forgot to mention I'm using an application called TestPlanner that automates some tasks for you by controlling the keyboard and mouse to accomplish "macro" like tasks.

The script itself actually opens and runs, but the problem is once the TestPlanner app runs, it's supposed to do a few things. One of which is to open the run window from the start menu and run another application... but for some reason the keys are never mapped to the text field within the run window and so the script fails.

So now I realize your ability to help me out can easily end here, because you probably have no idea what this TestPlanner application is...

The problem is that I am just an employee in a corporation, so there is no chance of me getting admin access. I don't think that's the problem though. I think that because the computer is in a locked state, the text field in the run command window can't be selected and so the script fails when it is trying to enter text into a field that cannot be selected. It looks like I just can't get a fix for that.

There's one last chance, you can try this, but I don't think it will work, see if the TestPlanner has the ability to 'allow service to interact with desktop'. In windows 2000, you could set this in the services control panel.

Honestly, I don't think that would solve your problem though. Since it's a macro program it most likely needs an unlocked console to work.

  • 0
  Joe USer said:
There's one last chance, you can try this, but I don't think it will work, see if the TestPlanner has the ability to 'allow service to interact with desktop'. In windows 2000, you could set this in the services control panel.

Honestly, I don't think that would solve your problem though. Since it's a macro program it most likely needs an unlocked console to work.

I just took a look at the program, and I unfortunately have found no such feature. Thanks for the suggestion though.

The funny thing is that although it can't select a text field to enter text into as part of the macro, it still successfully opens the Run command window via the "Windows key + R" shortcut.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • OBS Studio 31.1.0 Beta 2 by Razvan Serea OBS Studio is software designed for capturing, compositing, encoding, recording, and streaming video content, efficiently. It is the re-write of the widely used Open Broadcaster Software, to allow even more features and multi-platform support. OBS Studio supports multiple sources, including media files, games, web pages, application windows, webcams, your desktop, microphone and more. OBS Studio Features: High performance real time video/audio capturing and mixing, with unlimited scenes you can switch between seamlessly via custom transitions. Live streaming to Twitch, YouTube, Periscope, Mixer, GoodGame, DailyMotion, Hitbox, VK and any other RTMP server Filters for video sources such as image masking, color correction, chroma/color keying, and more. x264, H.264 and AAC for your live streams and video recordings Intel Quick Sync Video (QSV) and NVIDIA NVENC support Intuitive audio mixer with per-source filters such as noise gate, noise suppression, and gain. Take full control with VST plugin support. GPU-based game capture for high performance game streaming Unlimited number of scenes and sources Number of different and customizable transitions for when you switch between scenes Hotkeys for almost any action such as start or stop your stream or recording, push-to-talk, fast mute of any audio source, show or hide any video source, switch between scenes,and much more Live preview of any changes on your scenes and sources using Studio Mode before pushing them to your stream where your viewers will see those changes DirectShow capture device support (webcams, capture cards, etc) Powerful and easy to use configuration options. Add new Sources, duplicate existing ones, and adjust their properties effortlessly. Streamlined Settings panel for quickly configuring your broadcasts and recordings. Switch between different profiles with ease. Light and dark themes available to fit your environment. …and many other features. For free. At all. OBS Studio 31.1.0 Beta 2 changelog: Adjusted volume mixer styling on Classic theme [Warchamp7] Enabled font size option for macOS in appearance settings [gxalpha] Fixed an issue in Beta 1 where the projector menu for disabled preview was incorrect [Warchamp7] Fixed an issue in Beta 1 where opening appearance settings would enable the Apply button [Warchamp7] Fixed an issue in Beta 1 with menu bar padding [Warchamp7] Fixed an issue in Beta 1 with cut off text in Auto-Configuration Wizard [shiina424] Fixed an issue in Beta 1 with tab padding for new UI Appearance options [COOLIGUAY] Fixed an issue in Beta 1 where AMF AV1 B-frames did not work when using CQP [rhutsAMD] Download: OBS Studio 31.1.0 Beta 2 | Portable | ~200.0 MB (Open Source) View: OBS Studio Homepage | Other Operating Systems | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Brave 1.79.119 by Razvan Serea Brave Browser is a lightning-fast, secure web browser that stands out from the competition with its focus on privacy, security, and speed. With features like HTTPS Everywhere and built-in tracker blocking, Brave keeps your online activities safe from prying eyes. Brave is one of the safest browsers on the market today. It blocks third-party data storage. It protects from browser fingerprinting. And it does all this by default. Speed - Brave is built on Chromium, the same technology that powers Google Chrome, and is optimized for speed, providing a fast and responsive browsing experience. Brave Browser also features Brave Rewards, a system that rewards users with Basic Attention Tokens (BAT) for viewing opt-in ads. This innovative system provides an alternative revenue model for content creators and a way to support the Brave community. Brave 1.79.119 changelog: [Security] Added a conditional host check in binding handlers as reported on HackerOne by newfunction. (#46181) Fixed procedural filters not matching against dynamically added child elements. (#46208) Upgraded Chromium to 137.0.7151.68. (#46515) Download: Brave Browser 64-bit | 1.2 MB (Freeware) Download: Brave Browser 32-bit View: Brave Homepage | Offline Installers | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Here's every new AI feature Apple rumored to announce at WWDC 2025 by Hamid Ganji While Apple's WWDC event kicks off on June 9, Bloomberg's Mark Gurman has released a detailed report about every new AI feature Apple might unveil at the event. One of the most notable AI-related announcements at this year's WWDC is the Translate app. According to Gurman, Apple aims for a "systemwide push into translation" in iOS 26 while giving an AI boost to its Translate app. The app is expected to function as an Apple Intelligence feature and will be integrated into the operating system. The Translate app, initially designed for translating text, voice, and conversations, will focus on live translation of phone calls and text messages in iOS 26. Gurman also added that Apple is working on translating live conversations for AirPods wearers. Apple has a slew of AI-related announcements at WWDC 2025. For example, the iPhone maker reportedly allow third-party developers to access its Foundation Models to build AI features. Foundation Models are a suite of generative AI models behind Apple Intelligence features, including text summarization, Writing Tools, and Genmoji. Speaking of Genmoji, Gurman claims the feature in iOS 26 allows users to create a Genmoji by combining a pair of existing standard emoji. The Shortcuts app in iOS 26 also gets a touch of Apple Intelligence, allowing users to seamlessly create quick shortcuts for various actions using AI. Apple has seemingly prepared an upgraded version of the Foundation Models for both on-device and cloud use. These models will be announced at the WWDC, but developers can only access the on-device version. Today's report suggests that Apple will also introduce a new version of Xcode that taps into third-party LLMs. The feature is being tested internally using Claude models. According to Gurman, Apple's revamped Calendar app won't make it to this year's software and will debut on iOS 27 and macOS 27. Moreover, Apple's new Health app with AI recommendations has hit delays and won't be announced at the upcoming WWDC. The revamped app will be released at the earliest by the end of next year. Apple's battery optimization feature, which uses AI to save power on iPhones, may debut later this year with the iPhone 17 Air. Finally, Gurman says Apple is in talks with Google to add Gemini to iPhones as an alternative to OpenAI's ChatGPT. However, the collaboration won't be announced at this year's WWDC. Companies await the final ruling on Google's search deal with Apple.
    • WYSIWYG Web Builder 20.2.1 by Razvan Serea Web Buialder is a WYSIWYG (What-You-See-Is-What-You-Get) program used to create complete web sites. WYSIWYG means that the finished page will display exactly the way it was designed. The program generates HTML (HyperText Markup Language) tags while you point and click on desired functions; you can create a web page without learning HTML. Just drag and drop objects to the page position them "anywhere" you want and when youre finished publish it to your web server (using the build in Publish tool). Web Builder gives you full control over the content and layout of your web pages. One Web Builder project file can hold multiple web pages. Desktop publishing for the web, build web sites as easy as Drag & Drop "One Click Publishing" No FTP program needed. No special hosting required, use with any Hosting Service! Easily create forms using the built-in Form Wizard plus Form validation tools and built-in CAPTCHA. Advanced graphics tools like shapes, textart, rotation, shadows and many other image effects. Fully integrated jQuery UI (Accordion, Tabs etc), animations, effects and built-in ThemeRoller theme editor. Google compatible sitemap generator / PayPal eCommerce Tools Many navigation tools available: Navigation bars, tab menus, dropdown menus, sitetree, slidemenus. Built-in Slide Shows, Photo Galleries, Rollover images, Banners etc. Support for YouTube, Flash Video, Windows Media Player and many other video formats. Unique extension (add-on) system with already more than 250 extensions available! Create HTML5 / CSS3 websites today HTML5 document type (optimized HTML5 output). HTML5 audio/video and YouTube HTML5 support. HTML5 forms: native form validation, new input types and options, web storage. HTML5 canvas and svg support in shapes and other drawing tools. CSS3 @font-face. Use non web safe fonts in all modern browsers. CSS3 opacity, border radius, box shadow. CSS3 gradients. Add cool gradient effects using native CSS3 (no images). CSS3 navigation menu. Create awesome menus without using JavaScript or images. CSS3 animations and transitions. Including support for 2D and 3D transforms! Features for advanced users: Login Tools/Page Password Protection. Built-in Content Management System with many plug-ins (guestbook, faq, downloads, photo album etc). Add custom HTML code with the HTML tools. JavaScript Events: Show/hide objects (with animation), timers, move objects, change styles etc. Layers: Sticky layer, Docking layer, Floating layer, Modal layer, Anchored layer, Strechable layer and more! jQuery Theme Manager, create your own themes for the built-in jQuery UI widgets. Style Manager (global styling, H1, H2, H3 etc). Master Frames and Master Objects: reuse common element in your website. and much more! WYSIWYG Web Builder 20.2.1 changelog: Improved: Images in the properties of Photo Gallery, Photo Grid, Photo Collage and Slide Show can now be re-arrange using drag & drop. Improved: Default aspect ratio of HTML5 audio Fixed: Issue with list item icon offset in workspace. Fixed: 'Edit' button text in Login Admin cannot be changed. Fixed: Issue with Card max-width size calculation in breakpoints Fixed: Issue with (fixed) Layout Grid column height in breakpoints. Download: WYSIWYG Web Builder 64-bit | 30.1 MB (Shareware) Download: WYSIWYG Web Builder 32-bit | 28.0 MB Screenshot: >> Click here << Link: Home Page | Templates | Free extras/addons | Changelog Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      Vladimir Migunov earned a badge
      One Year In
    • One Month Later
      daelos earned a badge
      One Month Later
    • Week One Done
      daelos earned a badge
      Week One Done
    • Mentor
      Karlston went up a rank
      Mentor
    • One Month Later
      EdwardFranciscoVilla earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      494
    2. 2
      snowy owl
      252
    3. 3
      +FloatingFatMan
      250
    4. 4
      ATLien_0
      225
    5. 5
      +Edouard
      183
  • Tell a friend

    Love Neowin? Tell a friend!