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

如何编写通用PowerShell脚本映射NAS所有可访问网络共享?

修复后的PowerShell脚本:自动映射NAS可访问共享

以下是符合需求的可运行脚本,同时针对你原脚本的问题做了详细修复:

# 1. 收集NAS连接信息
$nasHostname = Read-Host "Enter NAS Hostname or IP Address"
$credential = Get-Credential -Message "Enter NAS Login Credentials"

# 2. 将凭据保存到Windows凭据管理器
$plainTextPassword = [System.Net.NetworkCredential]::new("", $credential.Password).Password
cmdkey /add:$nasHostname /user:$($credential.Username) /pass:$plainTextPassword

# 3. 建立到NAS的CIM会话
try {
    $cimSession = New-CimSession -ComputerName $nasHostname -Credential $credential -ErrorAction Stop
}
catch {
    Write-Error "Failed to connect to NAS: $_"
    exit 1
}

# 4. 获取用户可访问的非系统共享
$networkShares = Get-SmbShare -CimSession $cimSession | Where-Object {
    # 过滤系统默认共享
    $_.Name -notin @("ADMIN$", "IPC$", "C$", "D$") -and 
    $_.Path -notlike "*\sysvol" -and 
    $_.Path -notlike "*\netlogon"
}

if (-not $networkShares) {
    Write-Host "No accessible network shares found on $nasHostname"
    Remove-CimSession $cimSession
    exit 0
}

# 5. 获取当前已占用的驱动器字母
$usedDrives = Get-PSDrive -PSProvider FileSystem | Select-Object -ExpandProperty Name

# 6. 自动分配驱动器并映射所有共享
foreach ($share in $networkShares) {
    # 从Z开始反向查找第一个可用的驱动器字母
    $driveLetter = [char[]]('Z'..'A') | Where-Object { $_ -notin $usedDrives } | Select-Object -First 1
    
    if (-not $driveLetter) {
        Write-Warning "No available drive letters left, skipping share: $($share.Name)"
        continue
    }

    $sharePath = "\\$nasHostname\$($share.Name)"
    try {
        New-PSDrive -Name $driveLetter -Root $sharePath -Persist -PSProvider FileSystem -Credential $credential -ErrorAction Stop
        Write-Host "Successfully mapped: $sharePath -> $driveLetter`:"
        $usedDrives += $driveLetter
    }
    catch {
        Write-Warning "Failed to map $sharePath : $_"
    }
}

# 清理会话连接
Remove-CimSession $cimSession

原脚本的核心问题及修复说明

  1. CIM会话使用错误
    原脚本直接将NAS主机名传给Get-SmbShare的-CimSession参数,该参数需要的是通过New-CimSession创建的会话对象,而非字符串。修复后先建立合法的CIM连接,确保能正确获取NAS共享信息。

  2. 共享路径格式错误
    $share.Path是NAS本地的文件路径(如D:\Shares\Docs),而非网络访问路径。修复后用\\<NAS主机名>\<共享名>的标准格式生成网络路径。

  3. 密码类型不兼容
    $credential.Password是SecureString类型,cmdkey需要明文密码。通过System.Net.NetworkCredential类将SecureString转换为明文,适配cmdkey的要求。

  4. 驱动器名限制
    New-PSDrive的-Name只能是单个字母,且不能与现有驱动器冲突。修复后自动从Z到A反向查找可用字母,避免手动指定的冲突问题。

  5. 系统共享过滤
    原脚本会获取ADMIN$、IPC$等系统默认共享,这类共享无需映射。修复后添加过滤规则,仅保留用户实际可访问的业务共享。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:01:18