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?
Should do the trick,
Kindness,
Dan
Came here looking for how to map drives using PowerShell?
There's a simpler way with PowerShell3.0.
New-PSDrive
has been updated with the-persist
option. E.g.In the past,
New-PSDrive
affected only the current PowerShell session.-persist
causes the mapping to be registered with the O/S, as it were. See New-PSDriveTo answer the original question, you can vary the credentials used. Using
-Credential
to vary the domain\username causes Windows to prompt for a password. Another alternative is to pass a PSCredential object as in the example below. See Get-Credential for more detail.I found this easy one liner worked in my case (little "out of the box" thinking ;) )
(Start-Process -FilePath "C:\windows\system32\NET.exe" -ArgumentList "USE I: \Server\Volume /USER:XXXXX password /persistent:yes" -Wait -Passthru).ExitCode
And as an added bonus, you get an nice exitcode to report off of. Hope that helps.
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.:
On my workstation,
sent me error :
Curiously, it didn't come from the fact K: was already used but from "::" missing. Here's what's working on my workstation :