Convert LDIF to CSV with powershell

Guillaume C 1 Reputation point
2021-01-26T15:43:34.867+00:00

Hi,

I try to convert my sogo LDIF to CSV, but i have an issue, my LDIF content :

dn:
objectClass:
mail:
givenname:
sn:
displayname:
vcardcategories:

I want to exclude dn, objectclass, sn and vcardcategories

I use this script :

Get-Content $ldiffile |Foreach{
  $parts = $_.Split(":")
  switch($parts[0].Trim())
        {
            "dn" {
        if($obj -ne $null)
        {
            $objlist+=$obj
        }
        $obj=""| select mail,givenname,sn,dn,displayname
        $obj.dn=$parts[1].Trim()
    }
    "" {
      # Do nothing if it's blank
    }
    default {
      $obj."$($parts[0].Trim())"=$parts[1].Trim()
    }
  }


}
if ($obj -ne $null)
        {
            $objlist+=$obj
        }
$objlist| Export-Csv $destination

Do you know how can i only have these information in my CSV? (actually, my CSV is blank)

Thanks in davance

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,405 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,111 Reputation points
    2021-01-26T20:05:12.987+00:00

    Try this:

    $ldiffile = 'c:\junk\x.ldf'
    $destination = 'c:\junk\x.csv'
    $omit = 'dn','objectclass','sn','vcardcategories'
    $a = @{}                # initialize the temporary hash
    $x = @()                # results
    Get-Content $ldiffile |
        ForEach-Object {
            if ($_ -match "^\s*$") { # blank line - dump the hash and reinitialize the hash
                $x += [PSCustomObject]$a
                $a = @{ }
            }
            else {      # add the not-omitted key/value to the hash
                $key, $value = $_ -split ": "
                if ($omit -notcontains $key){
                    $a[$key] = $value
            }
        }
    }
    if ($a.keys.length -gt 0){  # emit last LDIF entry if LDIF didn't end w/blank line
        $x += [PSCustomObject]$a
    }
    $x | Export-Csv $destination -NoTypeInformation
    
    1 person found this answer helpful.