【问题标题】:Export-CSV powershell loop导出-CSV powershell 循环
【发布时间】:2012-09-27 23:55:17
【问题描述】:

从循环输出到 CSV 文件的正确做法是什么。我的目标是检查与一个多月未访问的一系列扩展名匹配的所有文件的属性,并输出到 csv 文件以供以后阅读。

它只输出第一个文件的信息。并出现以下错误:

Add-Member : Cannot add a member with the name "FileName" because a member with that name already exists. If you want to overwrite the member a
nyway, use the Force parameter to overwrite it.
At C:\Users\claw\Desktop\checkFileAge.ps1:10 char:25
+             $out2csv | add-member <<<<  -MemberType NoteProperty -Name FileName -Value $i.fullname
    + CategoryInfo          : InvalidOperation: (@{FileName=C:\u...012 9:33:46 AM}:PSObject) [Add-Member], InvalidOperationException
    + FullyQualifiedErrorId : MemberAlreadyExists,Microsoft.PowerShell.Commands.AddMemberCommand

这是我的例子:

    $out2csv = New-Object PSObject;

foreach ($i in get-childitem c:\users -recurse -include *.doc, *.xls, *.ppt, *.mdb, *.docx, *.xlsx, *.pptx, *.mdbx, *.jpeg, *.jpg, *.mov, *.avi, *.mp3, *.mp4, *.ogg) 
    {if ($i.lastaccesstime -lt ($(Get-Date).AddMonths(-1))) 
        {
            $out2csv | add-member -MemberType NoteProperty -Name FileName -Value $i.fullname
            $out2csv | add-member -MemberType NoteProperty -Name LastAccess -Value $i.LastAccessTime
        } 
    } $out2csv | Export-Csv "C:\FileAccessInformation.csv" -NoTypeInformation -Force

【问题讨论】:

    标签: loops powershell csv


    【解决方案1】:

    试试这样的。它是更规范的 PowerShell。

    $ext = '*.doc', '*.xls',...
    Get-ChildItem C:\Users -r -inc $ext | 
        Where {$_.LastAccessTime -lt [DateTime]::Now.AddMonths(-1)} |
        Select FullName, LastAccessTime |
        Export-Csv -NoTypeInformation -Force C:\FileAccessInformation.csv
    

    【讨论】:

    • 是否可以将 FullName 放入一个变量中,以便我可以将它与另一个函数一起使用?
    • 您可以在 Where cmdlet 之后将 Foreach 插入管道,例如Where ... | Foreach {$fn = $_.FullName; do stuff here with no output; $_} | ... 请注意,在 foreach 结束时,我输出了管道对象,以便可以在管道中进一步处理它。
    猜你喜欢
    • 2018-03-13
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多