如何在PowerShell中筛选映射驱动器的RemotePath属性以实现批量修改?
解决方案
问题原因
你之前写的Where-Object -FilterScript {'RemotePath'}中,过滤条件是固定字符串,布尔判断永远为真,所以过滤逻辑不会生效,会返回所有查询到的项。
正确筛选命令
查看所有带RemotePath属性的映射驱动器完整信息
Get-ChildItem -Path HKCU:\Network | Where-Object { $_.Property -contains 'RemotePath' }
直接提取盘符列表供循环调用
如果只需要拿到盘符(比如Z、Y这类驱动器名)用于后续批量操作,可以直接扩展PSChildName属性:
$mapDrives = Get-ChildItem -Path HKCU:\Network | Where-Object { $_.Property -contains 'RemotePath' } | Select-Object -ExpandProperty PSChildName
批量修改RemotePath示例
以下示例为将所有映射路径中的旧服务器名old-server替换为新服务器名new-server,可根据需求修改替换规则:
foreach ($drive in $mapDrives) { $regPath = "HKCU:\Network\$drive" # 读取当前远程路径 $currentRemotePath = Get-ItemPropertyValue -Path $regPath -Name RemotePath # 替换路径规则可自行调整 $newRemotePath = $currentRemotePath -replace '\\\\old-server\\', '\\new-server\' # 写入新的远程路径 Set-ItemProperty -Path $regPath -Name RemotePath -Value $newRemotePath }
内容的提问来源于stack exchange,提问作者Imtiaz Ali
相关产品推荐
相关产品推荐

