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

PowerShell多Get-SMB查询导出CSV为空 脚本问题排查求助

PowerShell SMB信息导出脚本问题修复

原有脚本核心问题

  • 数组定义逻辑冗余:你在$SmbCommands数组内直接执行了所有SMB查询命令并存储返回结果,后续的foreach循环完全无效,每次循环生成的对象内容完全重复,属于无用逻辑
  • 自定义对象属性名错误:构造对象时Select参数中错误使用$SmbInfo2这类变量作为属性名,而非固定的字符串属性名,导致对象结构异常
  • 复杂对象无法直接序列化:所有Get-SMB类命令返回的都是CIM实例对象,直接存入CSV只会显示对象类型字符串,不会输出实际的配置值
  • 导出配置缺失:Export-Csv未添加-NoTypeInformation参数会写入冗余类型头,未提前判断输出目录是否存在可能导致隐式执行失败

修正后的可用脚本

# 提前创建输出目录避免报错
$outputPath = "C:\Temp\SMBInfo.csv"
$outputDir = Split-Path $outputPath -Parent
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}

# 直接执行所有SMB查询命令
$SmbInfo1 = Get-SmbClientConfiguration
$SmbInfo2 = Get-SmbMapping
$SmbInfo3 = Get-SmbMultichannelConstraint
$SmbInfo4 = Get-SmbServerConfiguration
$SmbInfo5 = Get-SmbShare

# 构造自定义对象,将复杂对象转成JSON字符串保证CSV可正常写入
$outputObj = [PSCustomObject]@{
    SmbClientConfiguration = $SmbInfo1 | ConvertTo-Json -Compress
    SmbMapping = $SmbInfo2 | ConvertTo-Json -Compress
    SmbMultichannelConstraint = $SmbInfo3 | ConvertTo-Json -Compress
    SmbServerConfiguration = $SmbInfo4 | ConvertTo-Json -Compress
    SmbShare = $SmbInfo5 | ConvertTo-Json -Compress
}

# 导出到CSV,去掉冗余类型信息,指定UTF8编码避免乱码
$outputObj | Export-Csv -Path $outputPath -NoTypeInformation -Encoding UTF8

可选优化方案

如果你希望每个SMB命令的结果单独导出为一个CSV文件,可以使用以下逻辑:

$outputDir = "C:\Temp\SMBInfo"
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}

Get-SmbClientConfiguration | Export-Csv (Join-Path $outputDir "SmbClientConfiguration.csv") -NoTypeInformation -Encoding UTF8
Get-SmbMapping | Export-Csv (Join-Path $outputDir "SmbMapping.csv") -NoTypeInformation -Encoding UTF8
Get-SmbMultichannelConstraint | Export-Csv (Join-Path $outputDir "SmbMultichannelConstraint.csv") -NoTypeInformation -Encoding UTF8
Get-SmbServerConfiguration | Export-Csv (Join-Path $outputDir "SmbServerConfiguration.csv") -NoTypeInformation -Encoding UTF8
Get-SmbShare | Export-Csv (Join-Path $outputDir "SmbShare.csv") -NoTypeInformation -Encoding UTF8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:15:03