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.
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\shareSystem.Diagnostics.Process p =System.Diagnostics.Process.Start("net.exe", @"use H: \\server\share");p.WaitForExit();
// Gets the drive info, spits it out to the consoleDriveInfo info = new DriveInfo("H");Console.WriteLine(info.AvailableFreeSpace);
// Deletes the mapped drivep = 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.
$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.



