|
 Friday, October 12, 2007
« Auto-Insert Attribute Quotes in HTML | Main | The Ergonomic Consultant »

Map a Drive in .NET 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\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.

$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.

#    Comments [0] |
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview