Cannot access network drive in PowerShell running as administrator

前端 未结 7 1969
暗喜
暗喜 2020-12-07 13:23

I\'m running PowerShell in a Windows 7 x64 virtual machine. I have a shared folder on the host mapped as a network drive (Z:). When I run PS normally I can access that drive

7条回答
  •  情书的邮戳
    2020-12-07 13:56

    I'm using the following hacky solution where I recreate "missing" PSDrives in profile.ps1 when Powershell is running in elevated mode.

    Gist

    # Reconnect PSDrives for network connections when running with elevated privileges
    $elevated = (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    if( $elevated ) {
        net use | ?{ $_ -match ":\s+\\\\"  -and !$_.StartsWith("Unavailable") } | %{
            $tokens = $_.split(":")
            $psdrivename = $tokens[0][$tokens[0].length-1]
            $path = $tokens[1].trim().split(" ")[0].trim()
    
            if( !(get-psdrive | ?{ $_.Name -eq $psdrivename } )) {
                write-host ( "Restoring PSDrive for {0}: {1}" -f $psdrivename, $path )
                new-psdrive $psdrivename FileSystem $path | out-null
            }
        }
    }  
    

提交回复
热议问题