229 lines
9.4 KiB
PowerShell
229 lines
9.4 KiB
PowerShell
#Requires -Version 5.1
|
|
#Requires -RunAsAdministrator
|
|
|
|
<#
|
|
.SYNOPSIS
|
|
Lists saved network drive mappings for every local user profile.
|
|
|
|
.DESCRIPTION
|
|
Run in an elevated PowerShell window on the computer being inventoried.
|
|
Reads the Network key in each non-system user's registry hive. For unloaded
|
|
profiles, temporarily loads NTUSER.DAT (or NTUSER.MAN) under a unique HKU key
|
|
and unloads it in a finally block. Does not edit drive mappings or credentials.
|
|
|
|
Also enumerates mappings visible to this PowerShell logon session, unless
|
|
-SavedOnly is specified. These are NOT all other users' live mappings.
|
|
Saved mappings may be disconnected or obsolete. No shares are probed.
|
|
Temporary mappings in other sessions and unavailable profile containers
|
|
cannot be inventoried by this script. Accounts without local profiles are
|
|
not included. Warnings identify profiles that could not be fully scanned.
|
|
|
|
The script returns objects; use Format-Table for display or Export-Csv to save.
|
|
Use -Verbose to see the scan result for each profile, including empty profiles.
|
|
|
|
.EXAMPLE
|
|
$drives = .\Get-AllNetworkDrives.ps1 -Verbose
|
|
$drives | Format-Table User, Drive, RemotePath, Source -AutoSize -Wrap
|
|
|
|
.EXAMPLE
|
|
.\Get-AllNetworkDrives.ps1 | Export-Csv .\NetworkDrives.csv -NoTypeInformation -Encoding UTF8
|
|
#>
|
|
|
|
[CmdletBinding()]
|
|
param(
|
|
[switch]$SavedOnly
|
|
)
|
|
|
|
Set-StrictMode -Version 2.0
|
|
$ErrorActionPreference = 'Stop'
|
|
|
|
# Capture reg.exe failures without parsing localized success/error messages.
|
|
function Invoke-HiveCommand {
|
|
param(
|
|
[ValidateSet('load', 'unload')][string]$Action,
|
|
[string]$MountName,
|
|
[string]$HiveFile
|
|
)
|
|
|
|
$ErrorActionPreference = 'Continue'
|
|
$PSNativeCommandUseErrorActionPreference = $false
|
|
$regExe = Join-Path $env:SystemRoot 'System32\reg.exe'
|
|
$messages = if ($Action -eq 'load') {
|
|
& $regExe load "HKU\$MountName" $HiveFile 2>&1
|
|
} else {
|
|
& $regExe unload "HKU\$MountName" 2>&1
|
|
}
|
|
$exitCode = $LASTEXITCODE
|
|
[pscustomobject]@{
|
|
ExitCode = $exitCode
|
|
Message = ($messages | Out-String).Trim()
|
|
}
|
|
}
|
|
|
|
$results = [System.Collections.Generic.List[object]]::new()
|
|
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
|
|
Where-Object { -not $_.Special -and $_.SID } |
|
|
Sort-Object LocalPath)
|
|
|
|
if ($profiles.Count -eq 0) {
|
|
Write-Warning 'Windows reported no non-system user profiles.'
|
|
}
|
|
|
|
$usersKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
|
|
[Microsoft.Win32.RegistryHive]::Users,
|
|
[Microsoft.Win32.RegistryView]::Default
|
|
)
|
|
|
|
try {
|
|
foreach ($profile in $profiles) {
|
|
$sid = [string]$profile.SID
|
|
$userName = $sid
|
|
try {
|
|
$userName = ([System.Security.Principal.SecurityIdentifier]::new($sid)).Translate(
|
|
[System.Security.Principal.NTAccount]
|
|
).Value
|
|
} catch {
|
|
# Keep the SID when a deleted account or offline domain cannot resolve.
|
|
Write-Verbose "Account name unavailable for $sid; retaining its SID."
|
|
}
|
|
|
|
$profileKey = $null
|
|
$networkKey = $null
|
|
$mountedByScript = $false
|
|
$mountName = 'DriveInventory_' + [guid]::NewGuid().ToString('N')
|
|
$countBefore = $results.Count
|
|
|
|
try {
|
|
# Check the registry itself: the profile's Loaded flag can be stale.
|
|
$profileKey = $usersKey.OpenSubKey($sid, $false)
|
|
if ($null -eq $profileKey) {
|
|
if ([string]::IsNullOrWhiteSpace($profile.LocalPath)) {
|
|
throw 'The profile has no local path and its hive is not loaded.'
|
|
}
|
|
|
|
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.DAT'
|
|
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
|
|
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.MAN'
|
|
}
|
|
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
|
|
throw "Neither NTUSER.DAT nor NTUSER.MAN is available in $($profile.LocalPath)."
|
|
}
|
|
|
|
$loadResult = Invoke-HiveCommand -Action load -MountName $mountName -HiveFile $hiveFile
|
|
if ($loadResult.ExitCode -eq 0) {
|
|
$mountedByScript = $true
|
|
$profileKey = $usersKey.OpenSubKey($mountName, $false)
|
|
} else {
|
|
# The user may have signed in between our check and reg load.
|
|
$profileKey = $usersKey.OpenSubKey($sid, $false)
|
|
if ($null -eq $profileKey) {
|
|
throw "Could not load the profile hive: $($loadResult.Message)"
|
|
}
|
|
}
|
|
if ($null -eq $profileKey) {
|
|
throw 'The profile hive could not be opened after loading.'
|
|
}
|
|
}
|
|
|
|
$networkKey = $profileKey.OpenSubKey('Network', $false)
|
|
if ($null -ne $networkKey) {
|
|
foreach ($letter in $networkKey.GetSubKeyNames()) {
|
|
if ($letter -notmatch '^[A-Za-z]$') { continue }
|
|
$driveKey = $null
|
|
try {
|
|
$driveKey = $networkKey.OpenSubKey($letter, $false)
|
|
if ($null -eq $driveKey) {
|
|
throw "Drive key $letter disappeared during the scan."
|
|
}
|
|
$remotePath = [string]$driveKey.GetValue('RemotePath', '')
|
|
if ([string]::IsNullOrWhiteSpace($remotePath)) {
|
|
Write-Warning "${userName}: saved drive ${letter}: has no RemotePath."
|
|
continue
|
|
}
|
|
$results.Add([pscustomobject][ordered]@{
|
|
User = $userName
|
|
Drive = $letter.ToUpperInvariant() + ':'
|
|
RemotePath = $remotePath
|
|
Source = 'Saved'
|
|
ComputerName = $env:COMPUTERNAME
|
|
SID = $sid
|
|
ProfilePath = $profile.LocalPath
|
|
})
|
|
} finally {
|
|
if ($null -ne $driveKey) { $driveKey.Dispose() }
|
|
}
|
|
}
|
|
}
|
|
Write-Verbose ("{0}: {1} saved mapping(s) found." -f $userName, ($results.Count - $countBefore))
|
|
} catch {
|
|
Write-Warning "Incomplete scan for $userName [$sid], profile '$($profile.LocalPath)': $($_.Exception.Message)"
|
|
} finally {
|
|
# Close every child handle BEFORE unloading. Never unload an existing user hive.
|
|
if ($null -ne $networkKey) { $networkKey.Dispose() }
|
|
if ($null -ne $profileKey) { $profileKey.Dispose() }
|
|
if ($mountedByScript) {
|
|
$unloadResult = Invoke-HiveCommand -Action unload -MountName $mountName
|
|
if ($unloadResult.ExitCode -ne 0) {
|
|
Write-Warning "Could not unload HKU\$mountName. $($unloadResult.Message) After closing any handles, run: reg.exe unload HKU\$mountName"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
$usersKey.Dispose()
|
|
}
|
|
|
|
# Supplement saved mappings with those visible to THIS process's logon session.
|
|
# This can include temporary mappings, but only for the session running the script.
|
|
if (-not $SavedOnly) {
|
|
$identity = $null
|
|
$network = $null
|
|
$sessionDrives = $null
|
|
try {
|
|
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
|
|
$currentSid = $identity.User.Value
|
|
$network = New-Object -ComObject WScript.Network
|
|
$sessionDrives = $network.EnumNetworkDrives()
|
|
# WshCollection exposes Count as a COM method, not a PowerShell property.
|
|
for ($i = 0; $i -lt $sessionDrives.Count(); $i += 2) {
|
|
$drive = [string]$sessionDrives.Item($i)
|
|
$remotePath = [string]$sessionDrives.Item($i + 1)
|
|
if ($drive -notmatch '^[A-Za-z]:$') { continue }
|
|
|
|
$matchesSaved = @($results | Where-Object {
|
|
$_.SID -eq $currentSid -and $_.Drive -eq $drive -and $_.RemotePath -eq $remotePath
|
|
})
|
|
if ($matchesSaved.Count -gt 0) {
|
|
foreach ($match in $matchesSaved) { $match.Source = 'Saved + CurrentSession' }
|
|
} else {
|
|
$results.Add([pscustomobject][ordered]@{
|
|
User = $identity.Name
|
|
Drive = $drive.ToUpperInvariant()
|
|
RemotePath = $remotePath
|
|
Source = 'CurrentSession'
|
|
ComputerName = $env:COMPUTERNAME
|
|
SID = $currentSid
|
|
ProfilePath = $env:USERPROFILE
|
|
})
|
|
}
|
|
}
|
|
} catch {
|
|
Write-Warning "Could not fully enumerate current-session drives: $($_.Exception.Message)"
|
|
} finally {
|
|
if ($null -ne $sessionDrives) {
|
|
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($sessionDrives)
|
|
}
|
|
if ($null -ne $network) {
|
|
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($network)
|
|
}
|
|
if ($null -ne $identity) { $identity.Dispose() }
|
|
}
|
|
}
|
|
|
|
if ($results.Count -eq 0) {
|
|
Write-Warning 'No mappings were found in the sources successfully scanned. Review any earlier warnings; other sessions may still have temporary mappings.'
|
|
}
|
|
|
|
$results | Sort-Object User, Drive, RemotePath
|
|
|