Created
March 31, 2015 16:27
-
-
Save anderssonjohan/8d3f958f29b4ae5c7802 to your computer and use it in GitHub Desktop.
Profile.ps1 that fixes the problem with missing PSDrives when running Powershell with elevated privileges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reconnect PSDrives for network connections when running with elevated privileges | |
# Fixes http://stackoverflow.com/questions/4742992/cannot-access-network-drive-in-powershell-running-as-administrator | |
$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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@SeeCwriter You don't need semi-colons at the end of the line in PS; Only if you want to do several things on one line. Perhaps you have some bad line-endings or something?
I've hundreds of PS scripts that I use both on mac and windows and never had this issue.
This still works fine (today) with the original script on my win10 VM and it says:
If you want to try to see what's going on and see if PS interprets and runs any of the lines you can do so using
Set-PSDebug
.Before you run the script, make sure to execute
Set-PSDebug -Trace 2
. Don't forget to turn it off when you are done usingSet-PSDebug -Off
.Here is an example trace output that is generated that tells what the script/command is doing:
It will also tell about loops and iterations so if it doesn't find any drives to reconnect you would see that there as well.
Good luck!