0

I am trying to export Groupmembers list from azuread, my whole script works fairly well, but I need each new line in the final file to have the name of the file it is importing from (as well as the content it is importing)

the part of the script i am using to do this is as follows

(found this code here

Merging multiple CSV files into one using PowerShell)

get-childItem "C:\Users\user\Documents\Azure\Intune\management\*.csv" | foreach {

    $filePath = $_

    $lines =  $lines = Get-Content $filePath | Select -Skip 1
    $linesToWrite = switch($getFirstLine) {
           $true  {$lines}
           $false {$lines | Select -Skip 1}

    }

    $getFirstLine = $false
       Add-Content "C:\Users\user\Documents\Azure\Intune\management\master_list.csv" $linesToWrite
    }
Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33

2 Answers2

0

I would probably do something like this:

$files = Get-ChildItem -Path "C:\Users\user\Documents\Azure\Intune\management\*.csv"

ForEach ($file in $files) {
    Import-Csv -Path $File.FullName | 
        Select-Object -Property *, @{n='FileName';e={$file.Name}} | 
        Export-Csv -Path "C:\Users\user\Documents\Azure\Intune\management\master_list.csv" -NoTypeInformation -Append

}

Note that you need v3 or later of PowerShell to get the -Append flag for Export-Csv.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
0

Another way to do it. This way would be potentially memory intensive if the files are large but I like the method and it fits well with the way my brain works.

$result = New-Object System.Collections.ArrayList
foreach($file in Get-ChildItem 'C:\Users\User\Documents\Azure\InTune\Management\*.csv'){
  $result.AddRange((Import-CSV $file | Add-Member -InputObject $_ -Name 'File' -MemberType NoteProperty -Value $file.Name))
}
$result | Export-CSV 'C:\Users\user\Documents\Azure\Intune\management\master_list.csv' -NoTypeInformation

I think that would be version agnostic but I always lose track of which features happen in which version. Actually I think Add-Member would put it at v3+.

EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • Thanks for the answer, but does not seem to work for me, I get an error message when i run this, any ideas? dd-Member : Cannot bind argument to parameter 'InputObject' because it is null. At C:\Users\user\Documents\Azure\Intune\management\merge.ps1:3 char:64 + ... esult.AddRange((Import-CSV $file | Add-Member -InputObject $_ -Name ' ... + ~~ + CategoryInfo : InvalidData: (:) [Add-Member], ParameterBindingValidationException + FullyQualifiedErrorId : – adam humphrey Mar 23 '18 at 08:49
  • nevermind it does work, just for some reason did not work the first couple of times. not sure why. – adam humphrey Mar 23 '18 at 13:36
  • it was the file i already had there, once added a delete line, to remove the file before creating a new one, it was fine. – adam humphrey Mar 26 '18 at 13:03