如何使用凭据创建PSDrive?

时间:2016-11-14 14:18:20

标签: powershell share remote-access drive-mapping

当我连接到共享的“\\ ip_address \”文件夹而不使用凭据时,我成功连接:

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

当我为此命令指定凭据时:

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

我收到错误:

  

System.ComponentModel.Win32Exception(0x80004005):网络路径   没找到

这个错误是什么意思?
如何向用户请求凭据并使用它们映射远程共享文件夹?

操作系统: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

以下命令是好的:

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

以下命令不好:

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

2 个答案:

答案 0 :(得分:0)

尝试传入PSCredentials对象:

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

所以-Credential $cred
或使用:

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

答案 1 :(得分:0)

我希望我的功能符合您的需求。

Function ConnectTo-Domain()
    {
        $Domain = "my.domain.com"
        $DomainName = "MYDOMAIN"
        $userCred = $ENV:USERNAME

    do
    {
        # Get Domain Controllers of target domain

        $targetdomaindc = Get-ADDomainController -DomainName $Domain -Discover
        $targetdcname = $($targetdomaindc.hostname)

        # Authenticate with user providing password credential

        Write-Host "`nEnter $Domain credentials to get available Domain Controllers" -ForegroundColor Yellow
        $DCs = Get-ADDomainController -Filter * -Server $targetdcname -Credential (Get-Credential $Domain\$userCred)
    }
    until ($DCs -ne $NULL)

    $i = 0

    do
    {
        # Check that the target Domain Controller is available

        $testConnection = Test-Connection -ComputerName $DCs.Name[$i] -Count 2
        $currentDC = $DCs.Name[$i]
        $i++
    }
    until($testConnection -ne $NULL)

    # Check if an existing PSDrive exists and create if not

    $checkDrives = Get-PSDrive
    if ($checkDrives.Name -notcontains "$DomainName")
    {
        Write-Host "Enter $Domain credentials to connect to an available Domain Controller" -ForegroundColor Yellow
        New-PSDrive -Name $DomainName -PSProvider ActiveDirectory -Server $currentDC -Credential (Get-Credential $Domain\$userCred) -Root "//RootDSE/" -Scope Global
    }

    $DomainDriveName = $DomainName + ":\"
    cd $DomainDriveName
}