PowerShell New-PSDrive映射驱动器无法持久化问题排查
网络驱动器映射持久化问题解决
场景
创建计划任务执行以下PowerShell脚本自动映射Azure文件共享网络驱动器(敏感值已替换):
Write-Output "Made it to the start of the function" > C:\Temp3\result.txt $connectTestResult = Test-NetConnection -ComputerName foo.file.core.windows.net -Port 445 if ($connectTestResult.TcpTestSucceeded) { # Save the password so the drive will persist on reboot Write-Output "The test connection succeeded" > C:\Temp3\testconnection.txt cmd.exe /C "cmdkey /add:`"foo.file.core.windows.net`" /user:`"localhost\foo`" /pass:`"storageAccountPassword`"" > C:\Temp3\cmdresult.txt # Mount the drive New-PSDrive -Name Z -PSProvider FileSystem -Root "\\foo.file.core.windows.net\foofs" -Scope Global -Persist > C:\Temp3\mapdrive.txt } else { Write-Error -Message 'Unable to reach the Azure storage account via port 445. Check to make sure your organization or ISP is not blocking port 445, or use Azure P2S VPN, Azure S2S VPN, or Express Route to tunnel SMB traffic over a different port.' }
问题
脚本执行显示“成功”,但映射的Z盘无法在Windows资源管理器中显示;手动访问UNC路径无需验证,但新打开的资源管理器看不到驱动器。手动运行脚本(如PowerShell ISE)时,Z盘可正常显示并使用。
已尝试操作
- 手动运行脚本正常生效
- 添加日志验证各命令输出,未发现错误
- 按微软文档建议,在计划任务操作中使用点源方式执行脚本:
. C:\Temp3\mapNetworkFileShare.ps1
解决方法
1. 调整计划任务安全配置
计划任务默认在非交互式会话运行,导致驱动器仅在该会话可见,需修改:
- 打开计划任务属性,切换到「常规」标签,勾选**「不管用户是否登录都要运行」**,同时取消勾选「不存储密码」(需确保账户有本地管理员权限和Azure文件共享访问权限)
- 切换到「设置」标签,取消勾选「如果任务运行时间超过X小时就停止」(避免脚本被提前终止)
2. 替换脚本中的驱动器映射命令
New-PSDrive的-Persist参数在非交互式会话中兼容性不佳,改用net use命令实现持久化映射:
Write-Output "Made it to the start of the function" > C:\Temp3\result.txt $connectTestResult = Test-NetConnection -ComputerName foo.file.core.windows.net -Port 445 if ($connectTestResult.TcpTestSucceeded) { Write-Output "The test connection succeeded" > C:\Temp3\testconnection.txt # 使用net use创建持久化驱动器,替代cmdkey+New-PSDrive组合 net use Z: "\\foo.file.core.windows.net\foofs" "storageAccountPassword" /user:"localhost\foo" /persistent:yes > C:\Temp3\mapdrive.txt } else { Write-Error -Message '无法通过445端口连接到Azure存储账户。请确认组织或ISP未封锁445端口,或使用Azure P2S VPN、S2S VPN或Express Route通过其他端口传输SMB流量。' }
3. 修改计划任务的脚本执行参数
计划任务的「操作」配置需调整:
- 启动程序:
powershell.exe - 添加参数:
-ExecutionPolicy Bypass -File "C:\Temp3\mapNetworkFileShare.ps1"
(无需使用点源执行,非交互式场景下-File参数更可靠)
4. 修改注册表解决会话间驱动器可见性
若上述方法无效,通过注册表开启跨会话驱动器链接:
- 打开注册表编辑器(
regedit) - 定位到路径:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System - 右键新建DWORD(32位)值,命名为
EnableLinkedConnections - 将值设置为
1,重启电脑后生效
内容的提问来源于stack exchange,提问作者Christian Townsend
相关产品推荐
相关产品推荐

