首页 > 解决方案 > 映射后在资源管理器中打开驱动器

问题描述

一段时间以来,我一直在努力思考这种行为。

我在一个应该映射驱动器的模块中有一个 PowerShell 脚本,然后在文件资源管理器中打开它。

映射部分有效,但在尝试打开驱动器时出现错误:

ii:找不到驱动器。名为“L”的驱动器不存在。
在行:41 字符:9
+ ii "$($global:mapping_letter):"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (L:String) [Invoke-Item], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.InvokeItemCommand

奇怪的是,ii "$($global:mapping_letter):"在运行脚本后直接运行最终命令似乎没有问题。我认为该net use命令可能是异步的并Start-Sleep在命令之前尝试使用ii,但这会阻止驱动器甚至映射,直到它再次被唤醒。

代码如下:

function MapDrive {
    Param(
        [Parameter(Mandatory=$true,Position=0)]
        [string] $DrivePath,
        [Parameter(Mandatory=$false,Position=1)]
        [int] $notadmin,
        [Parameter(Mandatory=$false,Position=2)]
        [int] $disp
    )
    if (($admin-eq 0) -or ($admin-eq $null)) {
        if (-not $adminCredential) {
            GetadminCredentials
        }
    }

    #Find an available letter to map with
    [array]$letters = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
    $currentdrives = Get-PSDrive
    foreach ($letter in $letters) {
        if ($letter -notin $currentdrives.Name) {
            [array]$potential_letters += $letter
        }
    }
    $global:mapping_letter = $potential_letters | Get-Random -Count 1

    #Map the Drive
    $Uri = New-Object System.Uri($DrivePath)
    $IpAddress = Test-Connection ($Uri.Host) -Count 1 | Select -Expand IPV4Address | %{$_.ToString()}

    $PathName = $Uri.LocalPath -Replace $Uri.Host, $IpAddress

    #Remove Any Current Mapped Drive
    if (Test-Path "$($global:mapping_letter):") {
        Remove-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Scope Global -Force | Out-Null
        Start-Sleep -m 500
    }

    #Map the New Drive
    if (($notadmin -eq 0) -or ($notadmin -eq $null)) {
        #New-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Root $PathName -Credential $adminCredential -Scope Global -Persist | Out-Null
        net use "$($global:mapping_letter):" $PathName /user:$($adminCredential.username) /persistent:no | Out-Null
    } elseif ($notadmin -eq 1) {
        #New-PsDrive -Name $($global:mapping_letter) -PSProvider FileSystem -Root $PathName -Scope Global -Persist | Out-Null
        net use "$($global:mapping_letter):" $PathName /persistent:no | Out-Null
    }

    if (($disp -eq 1) -or ($disp -eq $null)) {
        ii "$($global:mapping_letter):"
    }
}

标签: powershelldrive-mapping

解决方案


推荐阅读