Connecting to a network folder with username/passw

2019-01-08 07:52发布

问题:

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?

回答1:

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

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.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either 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")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist


回答2:

This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:

net use \\server\share /user:<domain\username> <password>

And then do whatever you need to do in PowerShell...



回答3:

PowerShell 3 supports this out of the box now.

If you're stuck on PowerShell 2, you basically have to use the legacy net use command (as suggested earlier).



回答4:

On the same machine, I try the same NET USE command from a regular command prompt, and from a PowerShell v2 command prompt:

NET USE Link : SharePoint

In CMD it works just fine.

In PS, it says it works fine, and the drive is mapped. However, mostly the drive's status as listed when you type just NET USE is blank, and the drive mapping doesn't work (i.e. you cannot get data from the mapped drive).

It might be a SharePoint issue as the NET USE from powershell sometimes works, sometimes don't, but still it appears that there's a difference between CMD and PS.



回答5:

I would like to share my experience here.

I often use network drive to pull information from remote Server. If you are using Powershell 2.0 on remote Server.

Best option is to use NET USE command.

Net use \\10.10.10.10\SharedDrive "password@123" /User:Abcd.com\username


标签: powershell