sadia rehman
sadia rehman

Reputation: 61

How to get %username% in VBScript?

I am trying to hide network path of shared folders from domain users. (Windows Server 2012) I have found this script while searching for network drive labeling:

Option Explicit
Dim objNetwork, strDrive, objShell, objUNC
Dim strRemotePath, strDriveLetter, strNewName

strDriveLetter = "H:"
strRemotePath = "\\servername\sharedfoldername$\"
strNewName = "Save Your Files Here"

'Section to map the network drive
Set objNetwork = CreateObject("WScript.Network")
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath

'Section which actually (re)names the Mapped Drive
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strNewName

WScript.Echo "Check : "& strDriveLetter & " for " & strNewName
WScript.Quit

My network path will be like below:

strRemotePath = "\\servername\sharedfoldername1$\%username%"
strRemotePath = "\\servername\sharedfoldername2$\%username%"
strRemotePath = "\\servername\sharedfoldername5$\%username%"
strRemotePath = "\\servername\sharedfoldernameNNN$\%username%"

When I insert %username%, the script does not run.

Kindly guide me how to modify this script that will run as per my requirements.

Upvotes: 2

Views: 2322

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200463

You can expand environment variables in your path string:

strRemotePath = "\\servername\sharedfoldername1$\%username%"

Set sh = CreateObject("WScript.Shell")
WScript.Echo sh.ExpandEnvironmentStrings(strRemotePath)

or you can build the path from the share and the UserName property of the WshNetwork that you already have:

share = "\\servername\sharedfoldername1$"

Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.BuildPath(share, objNetwork.UserName)

Upvotes: 5

Related Questions