How to create PSDrive using credentials?

Egor Okhterov picture Egor Okhterov · Nov 14, 2016 · Viewed 10.1k times · Source

When I connect to shared "\\ip_address\" folder without using credentials I connect successfully:

$driveInfo = New-PSDrive `
  -Name $driveName `
  -PSProvider "FileSystem" `
  -Root $targetDirectory `
  -Scope "Script"

When I specify credentials for this command:

$driveInfo = New-PSDrive `
  -Name $driveName `
  -PSProvider "FileSystem" `
  -Root $targetDirectory `
  -Credential (Get-Credential) ` # Now ask credentials from user.
  -Scope "Script"

I get error:

System.ComponentModel.Win32Exception (0x80004005): The network path was not found

What does this error mean?
How can I ask credentials from user and use them to map the remote shared folder?


OS: Windows 10
PSVersion: 5.0.10586.672
BuildVersion: 10.0.10586.672
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1


The following command is good:

New-PSDrive -Name "test" -PSProvider FileSystem -Root "\\server.ru\"

The following command is bad:

New-PSDrive -Name "test" -PSProvider FileSystem -Root "\\server.ru\" -Credential (Get-Credential)

Answer

4c74356b41 picture 4c74356b41 · Nov 14, 2016

Try passing in a PSCredentials object:

$username = "domain01\admin01"
$password = cat C:\securestring.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $password

so -Credential $cred
or use:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")