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

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


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

Should do the trick,

Kindness,

Dan


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 userAdd-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


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.

New-PSDrive -Name U -PSProvider FileSystem -Root \\yourserver\your\folder -Credential yourdomain\username -Persist

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-PSDrive

To 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.

PS C:\> $User = "mydomain\username"PS C:\> $PWord = ConvertTo-SecureString -String "mypassword" -AsPlainText -ForcePS C:\> $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWordPS C:\> New-PSDrive -Name U -PSProvider FileSystem -Root \\domain\some\folder -Credential $Credential -Persist