创建自定义对象并使用输出
我使用以下内容从一整堆文本文件中读取一行,然后将该信息汇总到一个文件中。
$computers = Get-content computers.txt
$users = users.csv
$header = 'Computer','User','Date','Time'
Foreach ($computer in $computers)
{
$file = $computer +'.txt'
$a = import-csv $file -Header $header | Select -first 1
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Computer ($a.Computer)
$obj | Add-Member NoteProperty User ($a.User)
$obj | Add-Member NoteProperty Date ($a.Date)
$obj | Add-Member NoteProperty Time ($a.Time)
Write-Output $obj
$obj | Export-csv -path $users -notype
}
当我运行代码时,Write-Output 按预期输出所有记录,但 Export-CSV 仅包含最后一条记录。 我究竟做错了什么?
I'm using the following to read one line from a whole load of text files and then summarize that information into one file.
$computers = Get-content computers.txt
$users = users.csv
$header = 'Computer','User','Date','Time'
Foreach ($computer in $computers)
{
$file = $computer +'.txt'
$a = import-csv $file -Header $header | Select -first 1
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Computer ($a.Computer)
$obj | Add-Member NoteProperty User ($a.User)
$obj | Add-Member NoteProperty Date ($a.Date)
$obj | Add-Member NoteProperty Time ($a.Time)
Write-Output $obj
$obj | Export-csv -path $users -notype
}
When I run the code the Write-Output outputs all the records as expected, but the Export-CSV only contains the last record. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将在每次循环迭代时覆盖 csv 文件。 我相信以下给出了您假设每个 csv 文件只有四列(即计算机、用户、日期、时间)后的内容:
You are overwriting the csv file with each loop iteration. I believe the following gives what you're after assuming each csv file has only four columns (i.e Computer,User,Date,Time):
创建一个数组变量并将每个 $obj 添加到其中。 在 foreach 循环之后,导出对象数组,例如:
Create an array variable and add each $obj to it. After the foreach loop, export the array of objects e.g.: