I often access shared network folders in Powershell to grab files etc. But if the share requires a username/password, Powershell does not prompt me for these, unlike Windows Explorer. If I connect to the folder first in Windows Explorer, Powershell will then allow me to connect.
How can I authenticate myself in Powershell?
Back in Windows PowerShell 2, this was a problem. When you supplied credentials to the old New-PSDrive
...
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
Your best bet was to use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Since PowerShell 3 (in Windows 8 and Server 2012), the New-PSDrive
cmdlet now supports the -Credential
parameter properly, and has a -Persist
flag that makes these stick just like the other mechanisms.
If you call it with just a user name, it will prompt securely but interactively for the password:
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
Or you can pre-create credentials, if you have the password in a variable or text file:
$Password = ConvertTo-SecureString (Get-Content mypassword.txt) -AsPlainText
$Credential = [PSCredential]::new("user\domain", $Password)
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential $Credential -Persist