views:

1341

answers:

3

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?

+1  A: 

This should work:

$net = $(New-Object -ComObject WScript.Network) $net.MapNetworkDrive("r:", "\romeobox\files",,"username","password")

fpschultze
Thanks, just a note: the missing parameter before "username" caused PS to complain. Other than that it works!
dreftymac
+6  A: 
$net = new-object -ComObject WScript.Network$net.MapNetworkDrive '
("r:", "\\romeobox\files", $false, "domain\user", "password")

Should do the trick,

Kindness,

Dan

Daniel Elliott
+3  A: 

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
Keith Hill
+1 Good stuff; thanks for the info, Keith
Daniel Elliott