在PowerShell中捕获Net Use远程共享路径以解决驱动器映射问题
The core issue here is that Get-PSDrive and net use don’t always sync up when tracking mapped network drives. When you use net use /delete in your login script, it removes the drive at the Windows system level, but PowerShell’s Get-PSDrive might not immediately reflect that change. Conversely, your original logoff script relies on Get-PSDrive which can fail to capture the exact remote share path that net use recognizes.
To fix this, we’ll rewrite the logoff script to parse the output of net use directly—this gives us the exact remote share path that the net use command uses, ensuring full consistency between logoff and login actions.
Modified Logoff Script
# File path for saved drive mappings $TxtPath = "C:\temp\$env:UserName.txt" # Ensure the temp directory exists (create if missing) if (-not (Test-Path -Path "C:\temp")) { New-Item -Path "C:\temp" -ItemType Directory | Out-Null } # Clear existing entries in the file if it exists if (Test-Path -Path $TxtPath) { Clear-Content -Path $TxtPath } # Get all mapped network drives using net use, filter and parse the output $netUseOutput = net use | Select-String -Pattern "^([A-Z]):\s+\\\\.*$" foreach ($line in $netUseOutput) { # Extract drive letter and remote path from the matched line $driveLetter = $line.Matches.Groups[1].Value $remotePath = $line.Line.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries)[1] # Format entry to match your login script's split logic (Letter:;RemotePath) $entry = "$driveLetter:;$remotePath" Add-Content -Path $TxtPath -Value $entry }
What’s Changed & Why
- Switched to
net usefor drive detection: This ensures we capture the exact remote share path that thenet usecommand uses, eliminating sync gaps between PowerShell’s drive abstraction and Windows’ native drive mappings. - Added directory validation: The script now creates
C:\tempif it doesn’t exist, preventing errors when saving the mapping file. - Clean regex parsing: We use
Select-Stringwith a regex pattern to target only mapped network drives (lines starting with a drive letter followed by\\), then extract the relevant details without messy string splitting.
Your Login Script (With Minor Improvements)
You don’t need a full rewrite of your login script—since it already uses net use to delete and remap drives, it will work perfectly with the updated logoff script’s output. Here’s a tweaked version with quality-of-life improvements:
# File path for user drive paths $TxtPath = "C:\temp\$env:UserName.txt" # Only proceed if the mapping file exists if (Test-Path -Path $TxtPath) { # Get current drives to remove $DriveList = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-b:d-g:i-z]$' # Remove current drives silently (suppress confirmation prompts) ForEach($Item in $DriveList){ $Drive = "$Item:" net use $Drive /delete /y } # Map network drives from the saved file ForEach($Line in Get-Content $TxtPath) { $DriveLetter,$DrivePath = $Line.split(';') # Optional: Add /persistent:yes if you want drives to stay after reboot net use $DriveLetter $DrivePath /persistent:no } }
Key Notes
- The
/yflag innet use /deleteskips confirmation prompts, making the login script run silently in the background. - The
/persistent:noflag ensures drives aren’t saved across reboots—adjust toyesif you want persistent mappings. - Verify that the user running the scripts has write access to
C:\tempto avoid permission errors.
内容的提问来源于stack exchange,提问作者tacosnooper

