Map a Drive in .NET and PowerShell

by Donn Felker 11. October 2007 23:20

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Donn Felker

Senior Consultant
MCTS
ScrumMaster
Agile Practitioner

About Me | Books I Recommend

Gotta Pay The Bills


Tag cloud

    Popular Posts

    RecentComments

    Comment RSS

    Calendar

    <<  January 2009  >>
    MoTuWeThFrSaSu
    2930311234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678

    View posts in large calendar