Windows 2K3 Logon Script - Map Network Drive... VBScript and NET USE


Recommended Posts

Hi,

Long time reader... but infrequent poster - be kind!

Short Version

I want to create a log on script that maps \\Server\Users\%USERNAME%\%USERNAME%'s Documents\ to Z: and then have Windows Explorer pop up showing the new folder.

Long Version

Side Note

***I want to clear up now - when i set up the Roaming Profiles, i used the %USERNAME% variable (to move the profile folder to C:\Users Shared Folder\%USERNAME%\%USERNAME%'s Profile\) - but now with Windows XP and special folders, once in the user account, the %USERNAME%'s Documents folder doesnt show as Fred's Documents (for example), but "My Documents". So, i dont know in these scripts if i need to specify \%USERNAME%'s Documents or \My Documents***

I have a sever and a couple of workstations setup with Roaming User Profiles and "My Documents" all stored on the server. The file structure on the server is:

C:\Users Shared Folder\%USERNAME%\%USERNAME%'s Documents\

\%USERNAME%'s Profile\

So im trying to say the Profile and Documents are in the same folder (%USERNAME%) on the server, so all the information for each user (their documents and profile data) are stored in a folder on the server, called their username.

The server is Windows 2K3 SBS, workstations are XP Pro.

Ive been using this site for guidance.

What i want is to run a script at logon that will connect the "%USERNAME%'s Documents" folder (on the server) to a drive (say Z:) (on the user's workstation) and then open that Z drive in Explorer on the user's pc.

But using the link above i can only get to "\%USERNAME%\" (the folder above what i want). I want it to map straight to the "%USERNAME%'s Documents" folder, so the Profile folder isnt shown, as now the profile folder is shown by mapping to \%USERNAME%, (so they cant muck about with it).

What's the code? Im using the template below, but I have no idea of VBScript.

  Code said:
' MNDUserNameBonus.vbs

' VBScript to map a network drive to the UserName. And open Explorer

' Author Guy Thomas http://computerperformance.co.uk/

' Version 2.2 - September 2005

' -----------------------------------------------------------------'

Option Explicit

Dim objNetwork, objShell

Dim strDriveLetter, strRemotePath, strUserName

strDriveLetter = "X:"

strRemotePath = "\\grand\home\"

' Purpose of the script to create a network object. (objNetwork)

' Then to apply the MapNetworkDrive method. Result K: drive

Set objNetwork = WScript.CreateObject("WScript.Network")

' Here is where we extract the UserName

strUserName = objNetwork.UserName

objNetwork.MapNetworkDrive strDriveLetter, strRemotePath & strUserName

' Bonus code to open Explorer at the mapped drive letter

Call ShowExplorer

WScript.Quit

Sub ShowExplorer()

Set objShell = CreateObject("WScript.Shell")

objShell.run ("Explorer" & " " & strDriveLetter & "\" )

End Sub

' End of Example of MapNetworkDrive logon script.

I can use NET USE, and that works to map the drive with the %USERNAME% variable, but it dont know how to get it to open the folder afterwards. Also i dont know the differences of using NET USE (ie .cmd) compared to objNetwork.MapNetworkDrive (ie .vbs). Is there a way to combine the both commands? Or is there a way to complete both objectives using one of them? Whats the differnce between cmd and vbs files for logon scripts? Which are better?

Alot of questions i know, any help is appreciated.

Cheers

Edited by Major_Disaster
  kingofthecarts said:
So you want to map their "My Documents" to their My Documents on the Server? If I'm Correct.

No. Sorry if i wasnt clear.

I want to map the user's My Documents folder (which is stored on the server), to a drive (say Z:) on the workstations... so it appears in My Computer (My Documents on \\server\users for example).

Thanks for the quick reply.

  Major_Disaster said:
No. Sorry if i wasnt clear.

I want to map the user's My Documents folder (which is stored on the server), to a drive (say Z:) on the workstations... so it appears in My Computer (My Documents on \\server\users for example).

Thanks for the quick reply.

Can you make the users folder on the server their logon name example "jsmith"

Then share "jsmith" and remove "Everyone" and add only "jsmith" with full permissions

Then in their logon script. Just use

net use z: \\servername\%username% /persistant:yes /yes

Ahh Edit:... I see you want to open it afterwards, why not just add a shortcut to Z: in the startup folder...

Thanks for the reply - the quality, and quantity, of the help here is quite remarkable!

Well, tbh ive already managed to get a NET USE in much the way you have described to do the actual mapping - and it works. But this is only a small network, and im trying to learn new things and be a bit flashy... hence i was wanted to making the folder open in explorer once it has been mapped. For that i found:

  code said:
' MNDUserNameBonus.vbs

' VBScript to map a network drive to the UserName. And open Explorer

' Author Guy Thomas http://computerperformance.co.uk/

' Version 2.2 - September 2005

' -----------------------------------------------------------------'

Option Explicit

Dim objNetwork, objShell

Dim strDriveLetter, strRemotePath, strUserName

strDriveLetter = "X:"

strRemotePath = "\\grand\home\"

' Purpose of the script to create a network object. (objNetwork)

' Then to apply the MapNetworkDrive method. Result K: drive

Set objNetwork = WScript.CreateObject("WScript.Network")

' Here is where we extract the UserName

strUserName = objNetwork.UserName

objNetwork.MapNetworkDrive strDriveLetter, strRemotePath & strUserName

' Bonus code to open Explorer at the mapped drive letter

Call ShowExplorer

WScript.Quit

Sub ShowExplorer()

Set objShell = CreateObject("WScript.Shell")

objShell.run ("Explorer" & " " & strDriveLetter & "\" )

End Sub

' End of Example of MapNetworkDrive logon script.

But though that does show the folder after being mapped, it doesnt work with %USERNAME%.

I spose i could have one NET USE (.cmd file) and then just the Sub ShowExplorer() bit of the .vbs file? But thats kinda messy and i was wondering it there was a neater solution.

I realise im being fussy, but i just want to learn...

Thanks again

EDIT: Just saw your post. Yeah that would work. But what would be the code to add a shortcut to the startup folder?

  kingofthecarts said:
Or in the batch script you could add "explorer z:" Then it would open it.

Perfect. Thanks a bunch. Just what i wanted, and in only 2 lines of code!

A few questions though to satisfy my curiosity... weve managed to get this running with 2 lines of code, whereas the .vbs seemed to take 15 - how come the difference? Is one method "better" than the other?

Now to the desktop! Im wanting to put a few icons / links on the destop via logon script. I can make a folder on the server of links and then just use a logon script to copy them to the user's desktop folder easily enough (i hope) but how would i go about adding their "My Documents" folder to the desktop?

Something like this work?

Thanks for the continued help.

Much appreciated.

EDIT: Just saw your edit! I simply added

explorer Z:

to the logon script and it worked... what is the effect of "ECHO OFF"? (Be gentle - i see it all the time on the net, but only being a teenager i dont know anything before XP... so all these DOS commands are foreign to me... if indeed that is DOS related!)

"My documents" is the z: drive? right? Make a shortcut where the batch script is to the z: drive, then copy the shortcut over to the desktop?

Example:

xcopy "My Documents.lnk" "c:\documents and settings\%username%\desktop" ** Single User Desktop **
OR
xcopy "My Documents.lnk" "c:\documents and settings\all users\" **Put on ALL users Desktops **

Another way would be to redirect the "My Documents" folder path. Then show the "My documents" folder on the desktop.

ECHO OFF = Just Hides Stuff - Such as the command lines. But with a short script there is really no time to see anything :p

  kingofthecarts said:
"My documents" is the z: drive? right? Make a shortcut where the batch script is to the z: drive, then copy the shortcut over to the desktop?

Example:

xcopy "My Documents.lnk" "c:\documents and settings\%username%\desktop" ** Single User Desktop **
OR
xcopy "My Documents.lnk" "c:\documents and settings\all users\" **Put on ALL users Desktops **

Another way would be to redirect the "My Documents" folder path. Then show the "My documents" folder on the desktop.

ECHO OFF = Just Hides Stuff - Such as the command lines. But with a short script there is really no time to see anything :p

Thanks for carrying on putting up with me and all my questions! Its just that i find this interesting (odd eh?!)

Anyways, that worked well thanks - ive kinda modified it, as shown below:

xcopy "\\Server\Users\Desktop Shortcuts\My Documents.lnk" "%USERPROFILE%\Desktop"
xcopy "\\Server\Users\Desktop Shortcuts\My Computer.lnk" "%USERPROFILE%\Desktop"
xcopy "\\Server\Users\Desktop Shortcuts\Shared Documents.lnk" "%USERPROFILE%\Desktop"

But! When run a second time the a message comes up asking whether i want to overwrite (as the files are allready there). How do i stop this? Is this an "always answer yes" or "silent" or do i add that "ECHO OFF"?

Thanks again

  kingofthecarts said:
sorry got busy, kool, glad to help out :). I do this type of stuff alot :). , lol, forgot about %userprofile%.

Hope that helped ya :)

Yeh thanks a lot, you really helped. I dont do this stuff... at all. That was my first go at logon scripts, so not bad me thinks.

BTW, if anyone is interested, i found this. 3 Lines of VBScript allowing you to rename network drives.

So now i have 3 scripts that run:

1. Map To My Computer

(NET USE)

2. Rename Mapped Drives

mDrive = "N:\" etc

3. Desktop Shortcuts

XCOPY

Pretty cool!

  Joel said:
Why not do this in a GPO? You've chosen possibly the most complicated way to do this.

http://www.computerperformance.co.uk/w2k3/...er_redirect.htm

Eh? Ive allready set up roaming profiles and moved all the user data to the server.

I wanted (and have) now made it so whenever someone logs on they get a customised Desktop and My Computer.

/confused

My Documents redirection has nothing to do with roaming profiles. You've created a script to map the path when it's already a part of the GPO options. Why not use the tools provided for you instead of a script? Home folders are right there in each user's profile tab in AD.

Im glad i helped with that VBScript.

I think i now see what Joel meant about it being much easier to map the My Documents folder using Home Folders. Ive just fiddled with it now... so it basically just does NET USE DRIVELETTER: \\server\\my documents in a nice GUI way right? So just an easier way of putting the My Documents folder as a mapped drive in My Computer (on the client) without you having to make any scripts, right?

Ahh, looking at that link Joel posted i know see what he was talking about.

Ahh that looks rather clever... my next question was gona be how can i point all the start menu folders to the same location?!

Right, let me have a tinker with that and ill be back to report later.

Thanks again guys.

well, if you redirect "My documents" in GPO it should redirect the "my documents" to it's set location. (example: x:\%username%\my documents\") Or something along those lines.

Also (the reason I do Batch Scripts is because I have to do like 3 or 4 shares) GPO and AD settings I find are good for single share instances (IMO).

  kingofthecarts said:
Also (the reason I do Batch Scripts is because I have to do like 3 or 4 shares) GPO and AD settings I find are good for single share instances (IMO).

There's nothing wrong with batch scripts for shares, but redirecting system folders is best done in AD.

I have folder redirection set up for My Documents I then have the following in a Logon script.

Dim WSHShell

Set WSHShell = CreateObject("WScript.Shell")

myDrive = WSHShell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal")

Set objNetwork = CreateObject("WScript.Network")

objNetwork.MapNetworkDrive "U:" , myDrive

This reads where the My Documents for the current user is redirected to from the registry and then maps U Drive to the My Documents folder of the user. This ensures that if you change the location of folder redirection in GPO the map follows.

Hope it helps.

  G Man said:
I have folder redirection set up for My Documents I then have the following in a Logon script.

Dim WSHShell

Set WSHShell = CreateObject("WScript.Shell")

myDrive = WSHShell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal")

Set objNetwork = CreateObject("WScript.Network")

objNetwork.MapNetworkDrive "U:" , myDrive

This reads where the My Documents for the current user is redirected to from the registry and then maps U Drive to the My Documents folder of the user. This ensures that if you change the location of folder redirection in GPO the map follows.

Hope it helps.

Why use this over the settings in a GPO? :unsure:

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

    • No registered users viewing this page.
  • Posts

    • It's not. It's a rightwing lie peddled by liars to BillyBob'sFreedumb email chain. Feel free to provide any credible source to support this claim. You won't find a single one. The reason Biden wasn't prosecuted was because it was a handful of documents from the Obama years that were just in storage. And when the FBI asked for them, Biden and his team did everything they could to find them and return them immediately -- even ones the FBI didn't know were "missing". https://en.wikipedia.org/wiki/...assified_documents_incident Whereas the Charlatan in Chief stored mountains of classified material out in the open in his pay to play club infested with foreign spies. https://www.pbs.org/newshour/p...-mar-a-lago-shower-ballroom Trump also revealed this nation's most classified information to foreigners who had no clearance to access them...and then bragged about knowing them to their friends overseas. https://www.nbcnews.com/politi...arines-according-rcna119173 And not only are many still missing and not returned... https://www.cnn.com/interactiv...ssia-intelligence-trump-dg/ Trump denied having them to the FBI repeatedly and moved them around to avoid having to return them to the proper authorities for over a year. https://www.pbs.org/newshour/p...ing-of-classified-documents There is no credible legitimate comparison between the two classified documents cases. You might want to change the source of the information you are getting and falling for. They are obvious lying to you. PS On the content issue...I am a content creator. You and everyone else in world loves the franchises and content I have created and/or contributed meaningfully to. It's the studios that are doing everything they can to remove us, the content creators, from their balance sheets (now with AI)...not the people who consume what we create for free. We've already been paid, thanks. Blame Wall Street for forcing the bottomless greedy enshittification of everything American, not the consumers or the actual creators.
    • https://support.microsoft.com/...61ff-00a1-04e2-2d1f3865450d
    • https://support.microsoft.com/...61ff-00a1-04e2-2d1f3865450d
    • Swatle AI — the smarter way to manage your teams, projects, and tasks now 75% off by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 75% off on Swatle All-in-One AI Assistant (Premium lifetime subscription). Stop over-hiring and overspending to meet your productivity goals. Swatle is all you need to achieve more with less. Swatle is an all-in-one AI solution designed to supercharge your productivity without over-hiring or overspending. Whether you're managing projects, automating repetitive tasks, or organizing your team's workflow, Swatle can help you achieve more with less. Powered by cutting-edge artificial intelligence, it adapts to your needs, streamlines operations, and eliminates inefficiencies so you can focus on what matters most—growing your business. With Swatle, working smarter isn’t just a goal—it’s your new reality. Let Swatle AI handle the necessary mundane tasks. SWATLE AI PROJECT ASSISTANT Step-by-Step Guidance: For every task you assign, either write step-by-step instructions yourself or let Swatle AI write on your behalf Skip the Standups: Ask Swatle AI about project progress and get instant, actionable updates—no daily meetings needed Accurate Time Estimates: Plan your day better by estimating the time required to complete your tasks Message Refinement: Send crystal clear messages; Swatle AI will rephrase your message & make it crisp and clear Project Quality Boost: Turn normal project descriptions into a crystal-clear description TEAM COLLABORATION MADE EASY Streamline Communication: Send & receive messages and updates within Swatle for real-time, tool-free collaboration Centralized Team Portfolios: Create dedicated portfolios to highlight your team's expertise & track their contributions effectively Conversational Task Creation: Instantly create tasks while having casual conversations with a single click. Make sure nothing falls through the crack Share Files & Feedback Directly: Eliminate scattered documents and email threads by sharing files and providing feedback directly in Swatle chat SWATLE TASKDESK Non-Technical Projects: Specifically designed for projects like marketing campaigns, content creation, and event planning Visualize Work Your Way: Manage tasks through Kanban boards, lists, Gantt charts, or Timelines—whatever fits your flow AI Task Assistant: Break down complex tasks into manageable subtasks quickly & easily Workload Tracking: View the workload of your team members & distribute tasks across the team to encourage a balanced workload. Proactive Notifications: Effortlessly keep your projects on track with timely, proactive notifications SWATLE DEVBOARD Technical Projects: Create unlimited sprints & backlogs for full control and visibility into every phase of your projects Burndown Chart: Provides a clear, real-time visual representation of your team's work remaining against the sprint timeline Set Goals, Create Sprints, Achieve More: Define your objectives and launch focused sprints that empower your team to concentrate on key tasks within short, impactful cycles Why choose Swatle? No Learning Curve: Swatle offers a remarkably easy-to-use interface. Empower your entire team to understand project progress without requiring technical expertise. Actionable Intelligence: Swatle turns raw project data into visualizations, like Assigned vs Completed charts, enabling focused analysis without manual effort. Proactively Mitigate Risks: Swatle visual dashboards make it easy to spot potential delays, bottlenecks, and resource imbalances, enabling you to take timely action and keep your projects on track. Ensure Resources Are Optimized: By visualizing workloads, you can strategically distribute tasks, promote a balanced environment, and prevent team burnout. Maintain Project Alignment & Stakeholder Confidence: Keep everyone from your internal team to clients and stakeholders on the same page with clear Gantt and Timeline views. Good to know Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Max number of device(s): unlimited Available to both NEW and Existing users Updates included This Swatle All-in-One AI Assistant (Premium lifetime subscription) normally costs $240, but this deal can be yours for just $59.99, that's a saving of $180. For full terms, specifications, and license info please click the link below. Get this lifetime Swatle Premium deal for just $59.99 (75% off) or learn more 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

    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
    • Week One Done
      Prestige Podiatry Care earned a badge
      Week One Done
    • Week One Done
      rollconults earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      144
    2. 2
      Xenon
      128
    3. 3
      ATLien_0
      124
    4. 4
      +Edouard
      102
    5. 5
      snowy owl
      97
  • Tell a friend

    Love Neowin? Tell a friend!