Export-CSV Returning Thousands of Lines?

Wrote a script for work which migrates files from directory ‘x’ to directory ‘y’ depending on the -recurse output from a CSV.

Ran a test on 150 files and expected a result of only 150 lines – instead the csv generated returned with 4000 (yes, four thousand) lines of repeating data.

Here is essentially what I have with the try/catch block reiterating itself about 29 times for all our different variables on the files and actions:

$csv = import-csv 'C:Test.csv' $report = @() $csv | % { $record = $_ $column = New-Object PSObject try { $sourceDir = 'c:source' $sourceSub = $_.PSParentPath $fileName = $_.PSChildName $root = 'C:root' $destDir = "newdir" $destSub = "newdirsub" $sourceFile = $sourceDir + $sourceSub + $fileName if($_.FileAction -eq 'Other Group - Unknown'){ $destPath = $root + $destDir + $destSub + $sourceSub if (!(Test-Path -path $destPath)){ New-Item $destPath -ItemType directory -force } copy-item $sourceFile $destPath Write-Output ("MIGRATION SUCCESS - " + $fileName) $column | Add-Member NoteProperty PSParentPath ($record.PSParentPath) -Force $column | Add-Member NoteProperty PSChildName ($record.PSChildName) -Force $column | Add-Member NoteProperty DestDirectory ($destPath) -Force $column | Add-Member NoteProperty FileAction ($record.FileAction) -Force $column | Add-Member NoteProperty ScriptResult "Success" -Force } else { copy-item $sourceFile $destPath } } catch { Write-Output ("MIGRATION FAILED - " + $fileName) $column = New-Object PSObject $column | Add-Member NoteProperty PSParentPath ($record.PSParentPath) -Force $column | Add-Member NoteProperty PSChildName ($record.PSChildName) -Force $column | Add-Member NoteProperty DestDirectory ($destPath) -Force $column | Add-Member NoteProperty FileAction ($record.FileAction) -Force $column | Add-Member NoteProperty ScriptResult "Failed" -Force } finally { $report += $column } } $report | Export-Csv C:Movereport.csv -NoTypeInformation 

Could I be using the:

$column | Add-Member NoteProperty PSParentPath ($record.PSParentPath) -Force 

too many times? and if so how do I do it so that i don’t have to repeat the code over and over for every different variable.

End Goal – Export a csv w/ results of migration that ISN’T over 4000 lines of information on just 150 files.

EDIT 1: My workaround for this was to import the large CSV, use the -unique modifier and re-export it as a new file which returns only the results I want. I want to skip this step and somehow have the export work correctly the first time.

submitted by /u/BananasAndPears
[link] [comments]

Leave a Reply