PowerShell: Mapping and Unmapping Network Drives

How to Map Network Drive using Dot Net Framework
$driveLetter='T'
$smbPath='\\FILESERVER\SHARENAME'
$username='DOMAIN\USERNAME'
$password='PASSWORD'
$networkDrivesObject = new-object -ComObject WScript.Network
$networkDrivesObject.MapNetworkDrive($driveLetter, $smbPath, "true", $username, $password)
How to Remove Network Drive using Dot Net Framework
$driveLetter='T'
$networkDrivesObject = new-object -ComObject WScript.Network
$networkDrivesObject.RemoveNetworkDrive("$driveLetter`:",$True,$True) # Unmap
Troubleshooting

Errors:

Exception calling "RemoveNetworkDrive" with "3" argument(s): "This network connection does not exist.
"
At line:1 char:1
+ $networkDrivesObject.RemoveNetworkDrive("$driveLetter`:",$True,$True)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

$driveLetter='T'
Remove-PSDrive $driveLetter -PSProvider FileSystem -Scope Global -Verbose

VERBOSE: Performing the operation "Remove Drive" on target "Name: T Provider: Microsoft.PowerShell.Core\FileSystem
Root: T:\".

Remove-SMBMapping $driveLetter -Force -verbose

Remove-SMBMapping : No MSFT_SmbMapping objects found with property 'LocalPath' equal to 'T'.  Verify the value of the
property and retry.
At line:1 char:1
+ Remove-SMBMapping $driveLetter -Force -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (T:String) [Remove-SmbMapping], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound_LocalPath,Remove-SmbMapping

Resolution:

Simply reboot the computer and retry the Remove-PSDrive $driveLetter command.

Leave a Reply

Your email address will not be published. Required fields are marked *