Powershell: how to map a network drive with a different username/password

If you need a way to store the password without putting it in plain text in your script or a data file, you can use the DPAPI to protect the password so you can store it safely in a file and retrieve it later as plain text e.g.:

# Stick password into DPAPI storage once - accessible only by current user
Add-Type -assembly System.Security
$passwordBytes = [System.Text.Encoding]::Unicode.GetBytes("Open Sesame")
$entropy = [byte[]](1,2,3,4,5)
$encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect( `
                       $passwordBytes, $entropy, 'CurrentUser')
$encrytpedData | Set-Content -enc byte .\password.bin

# Retrieve and decrypted password
$encrytpedData = Get-Content -enc byte .\password.bin
$unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( `
                       $encrytpedData, $entropy, 'CurrentUser')
$password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData)
$password

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("r:", "\\romeobox\files", $false, "domain\user", "password")

Should do the trick,

Kindness,

Dan