Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Background: Assume I use the following powershell script from my local machine to automatically map some network drives.

$net = $(New-Object -ComObject WScript.Network);
$net.MapNetworkDrive("p:", "\\papabox\files");

$net = $(New-Object -ComObject WScript.Network);
$net.MapNetworkDrive("q:", "\\quebecbox\files");

## problem -- this one does not work because my username/password
## is different on romeobox
$net = $(New-Object -ComObject WScript.Network);
$net.MapNetworkDrive("r:", "\\romeobox\files");

Question: How do I modify the script so that I can also connect to romeobox, even though my username/password on romeobox is different from that of the other two boxes?

like image 939
dreftymac Avatar asked Oct 07 '09 10:10

dreftymac


2 Answers

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
like image 39
Keith Hill Avatar answered Sep 23 '22 04:09

Keith Hill


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

Should do the trick,

Kindness,

Dan

like image 91
Daniel Elliott Avatar answered Sep 23 '22 04:09

Daniel Elliott