0

What is the correct practice on outputting to a CSV file from a loop. My goal is to check the attributes of all files matching a series of extensions that have not been accessed in over a month and output to a csv file for reading later.

it only outputs the information for the first file. and errors the following:

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

Here is my example:

    $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

1 Answer 1

2

Try something like this. It is a bit more canonical 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
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to get the FullName into a variable so that I can then use it with another function?
You can stick in a Foreach into the pipe after the Where cmdlet e.g. Where ... | Foreach {$fn = $_.FullName; do stuff here with no output; $_} | ... Note that at the end of the foreach, I output the pipeline object so it can be processed further down the pipeline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.