June 8, 2009

Connect to Network Drive using Powershell

In one of my applications using powershell, I often have to connect to various network drives. I saw that powershell has a cmdlet called New-PSDrive which should take care of this for me. However, I saw that it kept failing on the connection with the provider does not support the use of credentials. How am I going to connect without being able to use the -credential option?! Well, I figured I'd have to script it using posh and calling something else. This is what I came up with:
# Map a Drive and pass in the below params
function MapNetworkDrive($net_drive, $path, $user, $password) {
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive($net_drive, $path, $false, $user, $password)
}

function RemoveNetworkDrive($net_drive){
try
{
$net = new-object -ComObject WScript.Network
$net.RemoveNetworkDrive($net_drive)
}
catch [System.Exception]
{
#Log
}
}

No comments:

Post a Comment