• 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

    • I have checked the scaling, and it is not different at all I reapplied my current theme and no thing changed.   Fonts still too damn small and NO OPTION IN WINDOWS TO ADDRESS IT ANYMORE!   Removing options for customization is NOT UPGRADING IN ANYWAY!
    • Hopefully this will turn out to be the same/better than the old LOTR BFME series. Been nothing decent on the RTS scene for a long time now. Anything that does come out tends to be pretty mediocre. A new C&C Generals series would sell well
    • It make sense only if they want to hide the minority of changes of each new version
    • Trade up with Sterling Stock Picker now price dropped by 85% by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 85% off on a lifetime subscription to Sterling Stock Picker. Sterling Stock Picker (SSP) is an award-winning platform designed to make stock investing accessible to everyone, regardless of expertise. The software offers multiple methods to identify winning stocks that align with your personal values, investment preferences, and risk tolerance. By handling all the complex calculations, it allows you to focus on making informed investment decisions. The patent-pending North Star technology provides clear guidance on whether to buy, sell, hold, or avoid a particular stock. Ask Finley, your personal AI financial coach Finley is your personal AI financial coach providing real-time data access, strategic investment advice, risk assessment, and educational support to help you make informed decisions. Whether you're a seasoned investor or just starting, Finley is equipped to help you achieve your financial goals. Feel free to ask any questions about your portfolio or the stock market. PERSONALIZED FINANCIAL GUIDANCE Custom Recommendations: Get stock picks tailored to your risk tolerance, portfolio performance, and investment goals. Dynamic Insights: Access detailed financial, technical, earnings, growth, and risk analysis for smarter investing. ENHANCED PORTFOLIO MANAGEMENT Done-For-You Portfolio Builder: Easily construct a diversified portfolio based on your risk tolerance and investment goals. Analysis and Suggestions: Receive data-driven portfolio adjustments to optimize returns based on your risk acceptance score. Risk Assessment Overview: Understand your risk level and receive stock recommendations aligned with your investment strategy. STRATEGIC INVESTMENT ADVICE Stock Rockets: Discover top-performing companies with over 50% quarterly revenue growth and the highest North Star rankings. Concentrated Portfolio Strategy: Focus on high-potential stocks instead of broad diversification to maximize growth. Industry and Sector Insights: Stay ahead with detailed performance narratives and sector-specific trends. EDUCATIONAL SUPPORT & COMMUNITY Verbose Explanations: Break down complex financial concepts with in-depth explanations for beginners. Investment Strategies: Learn and apply various investment strategies with expert-backed insights. Community Chat Forum: Connect with fellow investors to share insights, ask questions, and discuss investment strategies. Build your Stock Portfolio in 3 easy steps! Discover Your Risk Tolerance: Take a quick 5-minute questionnaire to assess your ability to handle risk effortlessly. Search Stocks Aligned With Your Personal Values: Use an intuitive stock-picking interface to confidently find winning stocks. Build Your Portfolio: Utilize the Done-For-You Portfolio Builder to simplify investing and remove the guesswork. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Only available to new users Updates included A lifetime subscription to Sterling Stock Picker normally has a suggested price of $486, but you can pick it up for just $68.99 for a limited time - that represents a saving of $417 (85% off). For a full description, specs, and license info, click the link below. Sterling Stock Picker lifetime subscription for $68.99 (was $486) Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      492
    2. 2
      +FloatingFatMan
      256
    3. 3
      snowy owl
      248
    4. 4
      ATLien_0
      224
    5. 5
      +Edouard
      189
  • Tell a friend

    Love Neowin? Tell a friend!