← All articles

Map a Drive in .NET and PowerShell

Quick code snippets for mapping, checking, and deleting a network drive at runtime, shown both in .NET (System.Diagnostics.Process) and PowerShell.

Donn Felker

Donn Felker

2007.10.12 · 1 min read

I recently had to Map a drive during runtime. I purused around the .NET Framework and I didn’t find anything so I wrote a quick little snippet of code to do it for me.

CODE TO MAP A DRIVE, GET DETAILS AND DELETE IT IN .NET

// Maps the "H" Drive to \\server\share
System.Diagnostics.Process p =
System.Diagnostics.Process.Start("net.exe", @"use H: \\server\share");
p.WaitForExit();
// Gets the drive info, spits it out to the console
DriveInfo info = new DriveInfo("H");
Console.WriteLine(info.AvailableFreeSpace);
// Deletes the mapped drive
p = System.Diagnostics.Process.Start("net.exe", @"use H: /DELETE");
p.WaitForExit();

Explanation

Its quite simple when we get down to it. We’re mapping the drive the same way you’d normally do it from the command line. Opening up the net.exe app, passing in the use command and then the drive letter.

I then spit out some information about the drive and then give an example of how to delete the mapped drive.

POWERSHELL

Here’s how to do it in PowerShell.

Terminal window
$net = $(New-Object -Com WScript.Network)
$net.MapNetworkDrive("u:", "\\computer\share")

Note, you can use the New-PsDrive command to map a drive in PowerShell, but that will only exist within the runspace that the PowerShell instance created it in. It will not map a drive that is usable by Windows Explorer or a GUI.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading