Share via

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 for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 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
    
    2 people found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.