#PSTip Create mapped network drive using WScript.Network

There are multiple methods of mapping network drives in PowerShell. In the past the net.exe tool was used and since PowerShell 3.0 drives can be persistently mapped using the New-PSDrive cmdlet. There is a third option available using the MapNetworkDrive method of WScript.Network COM object.

An example of how a drive can be mapped can be seen here:

(New-Object -ComObject WScript.Network).MapNetworkDrive('Z:','\\server\folder')

This will not map the drive persistently. In other words, the drive will disappear after reboot or when a user logs out. To ensure the drive mapping is persistent a third argument should be added–a Boolean value set to true:

(New-Object -ComObject WScript.Network).MapNetworkDrive('Z:','\\server\folder',$true)

It is also possible to specify a username and password. Unfortunately, both the username and password have to be supplied as plain text. An example of how to map a drive using alternate credentials:

(New-Object -ComObject WScript.Network).MapNetworkDrive('Z:','\\server\folder',$true,'domain\user','password')

A drive mapping might already be present using the drive letter that we want to use for the new mapped drive. The RemoveNetworkDrive method of the WScript.Network object can be utilized to remove a mapped network drive:

(New-Object -ComObject WScript.Network).RemoveNetworkDrive('Z:')

When there are open connections to the mapped drive, an error will be thrown when executing the previous command. To forcefully disconnect a drive mapping add $true as the second argument.

(New-Object -ComObject WScript.Network).RemoveNetworkDrive('Z:',$true)

For more details about these two methods and available arguments see the following articles on MSDN:

MapNetworkDrive: http://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx

RemoveNetworkDrive: http://msdn.microsoft.com/en-us/library/d16d7wbf(v=vs.84).aspx

Share on: