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

PowerShell脚本Export-CSV生成独立CSV异常及无数据问题求助

PowerShell脚本错误排查与修复

原脚本的核心错误点

  • 变量定义时机错误:$source = "\\$computer\c$" 写在foreach循环外部,此时$computer还未被赋值,导致$source是无效的空值。
  • 路径重复拼接:循环内Get-ChildItem的路径写成"\\$Source\c$",但$source本身已经是\\$computer\c$,最终路径变成\\\\$computer\c$\c$,完全无法访问目标共享目录,自然拿不到任何文件数据。
  • 潜在文件名问题:若$computer包含斜杠、星号等特殊字符,会导致导出的CSV路径非法;最初仅生成单个CSV的问题,也是因为循环外部变量错误,所有迭代都复用了同一个无效的$source,最终只生成一个空文件。

修正后的脚本

$computers = Get-Content "pathway.txt"
$exportRootPath = "C:\path"

# 确保导出目录存在,避免因目录缺失报错
if (-not (Test-Path -Path $exportRootPath)) {
    New-Item -ItemType Directory -Path $exportRootPath | Out-Null
}

foreach ($computer in $computers) {
    # 清理主机名/IP中的非法字符,避免文件名过长或无效
    $sanitizedName = $computer -replace '[\\/:*?"<>|]', '_'
    $exportPath = Join-Path -Path $exportRootPath -ChildPath "$sanitizedName.csv"

    # 直接在循环内构造正确的共享路径
    $sharePath = "\\$computer\c$"
    
    Get-ChildItem -Path $sharePath -Recurse -Force -ErrorAction SilentlyContinue |
        Select-Object Name, Extension, FullName, CreationTime, LastAccessTime, LastWriteTime, Length |
        Export-Csv -Path $exportPath -NoTypeInformation
}

额外说明

  • 新增导出目录检查逻辑,避免因目录不存在导致的导出失败。
  • 对$computer进行非法字符替换,解决文件名过长或路径非法的问题。
  • 循环内直接构造共享路径,彻底避免变量提前赋值引发的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:05:17