Friday, February 14, 2014

PowerShell: Find Current Remote User Mapped Drives

I thought it would be simple to find someone's current drive mappings using PowerShell.  This wasn't the case.  When I used my credentials to remotely access the computer, it looked for the mapped drives of the credentialed user, not the current user.  After much research and testing, I found a solution that you can customize to your environment.  This script was tested in a Windows 7 Enterprise Active Directory environment using PowerShell 4.0 on the script side and PowerShell 2.0 on the client side.  Here is the script with explanations:

$computer = "remotecomputername"
$creds = get-credential

#Find the remote computer's current user and cut off the 
#domain part of the username
$user = (gwmi win32_computersystem -computer $computer -credential $creds).username.split('\')[-1]
#Query Active Directory using $user to find the users SID

$sid = (get-aduser $user).sid.value

#Run a remote script while inputting the user SID (variable at bottom of script)
invoke-command -computer $computer -credential $creds -scriptblock {
#Remote HKCU & HKLM are only loaded.  
#We're adding the HKEY_USERS key so we can query against it

set-location registry::\HKEY_USERS
New-PSDrive HKU Registry HKEY_USERS
Set-Location HKU:

#Find all mapped drive letters in the \network key
$drives = (gci -Path Microsoft.PowerShell.Core\Registry::HKEY_USERS\$($args[0])\Network -recurse)
#Read the RemotePath key from each mapped drive
$driveresults = foreach ($d in $drives){$q = ("Microsoft.PowerShell.Core\Registry::HKEY_USERS\$($args[0])\Network\" + $d.pschildname);get-itemproperty -Path $q;}
#You can manipulate the output to your needs and assign this whole invoke-command script to a variable for further formatting
$driveresults|Format-Table PSChildName,RemotePath -autosize -hidetableheaders} -argumentlist $sid