You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PowerShell中捕获Net Use远程共享路径以解决驱动器映射问题

Fixing Drive Mapping Sync Between Logoff/Login Scripts

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 use for drive detection: This ensures we capture the exact remote share path that the net use command uses, eliminating sync gaps between PowerShell’s drive abstraction and Windows’ native drive mappings.
  • Added directory validation: The script now creates C:\temp if it doesn’t exist, preventing errors when saving the mapping file.
  • Clean regex parsing: We use Select-String with 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 /y flag in net use /delete skips confirmation prompts, making the login script run silently in the background.
  • The /persistent:no flag ensures drives aren’t saved across reboots—adjust to yes if you want persistent mappings.
  • Verify that the user running the scripts has write access to C:\temp to avoid permission errors.

内容的提问来源于stack exchange,提问作者tacosnooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:07:03