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

如何让PowerShell将Get-ChildItem结果输出为指定字段的CSV文件

问题原因

你当前代码的核心问题是Get-ChildItem返回的是匹配到的所有文件的对象数组,你直接把整个数组的Name、LastWriteTime属性赋值给单个PSObject,导出CSV时只会保存属性的集合类型标识,无法正确写入每个文件的对应字段。

修复后的完整代码
$pc = Get-WmiObject Win32_ComputerSystem
$files = Get-ChildItem -Path S:\Docker\RCT\repo\*xml -Recurse -Force 
$DeviceObjList = @()

# 遍历每个文件生成对应对象
foreach ($file in $files) {
    $DeviceObj = New-Object PSObject -Property @{
        DeviceName = $pc.Name
        FileName = $file.Name
        FileDate = $file.LastWriteTime
    }
    $DeviceObjList += $DeviceObj
}

$DeviceObjList | Export-Csv -Path "$current_path\FileStatus.csv" -NoTypeInformation -Encoding UTF8
更简洁的管道实现(可选)

你也可以直接通过Select-Object的计算属性处理结果,不需要手动维护数组和循环,代码更高效:

$pcName = (Get-WmiObject Win32_ComputerSystem).Name
Get-ChildItem -Path S:\Docker\RCT\repo\*xml -Recurse -Force | 
    Select-Object @{Name='DeviceName';Expression={$pcName}},
                @{Name='FileName';Expression={$_.Name}},
                @{Name='FileDate';Expression={$_.LastWriteTime}} |
    Export-Csv -Path "$current_path\FileStatus.csv" -NoTypeInformation -Encoding UTF8
注意事项
  • 请提前为$current_path变量赋值,你可以使用$current_path = $PSScriptRoot快速获取当前脚本所在目录作为导出路径,避免路径错误。
  • Windows PowerShell(5.1及以下版本)中-Encoding UTF8会生成带BOM的UTF8文件,如需无BOM的UTF8文件可升级到PowerShell 7+版本,或单独调整编码参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:06:01