Parse ldif data to CSV format using PowerShell

EspnHaj15 1 Reputation point
2022-11-20T23:54:02.097+00:00

Hello, I am attempting to parse ldif data to CSV format. I have tried my hand at this for sometime but haven’t came up with anything remotely close.

I have also tried solution below which does not work for my situation.
https://learn.microsoft.com/en-us/answers/questions/245854/convert-ldif-to-csv-with-powershell.html

My scenario is I have ldif file formatted like below:

dn: cn=groupName,ou=subOuName,ou=ParentOu,o=org
.net
uniquemember: uid=logonName1
uniquemember: uid=logonName2
uniquemember: uid=logonName3

dn: cn=OthergroupName,ou=subOuName,ou=ParentOu,o=org
.net
uniquemember: uid=logonName1
uniquemember: uid=logonName2
uniquemember: uid=logonName3

How can I convert the above ldif data to csv format like below?

UID,GNAME
 #headers
logonName1,groupName

logonName2,groupName

logonName3,groupName

logonName1,OthergroupName

logonName2,OthergroupName

logonName3,OthergroupName

Please note I am not querying AD, so I cannot use AD commands from the ActiveDirectory module.

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,449 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 45,671 Reputation points
    2022-11-21T02:57:27.637+00:00

    Try this:

    $ldiffile = 'c:\junk\xx.ldf'  
    $destination = 'c:\junk\xx.csv'  
      
    $regex1 = 'CN=(.*?(?<!\\)),(.*)'  
    $regex2 = 'UID=(.*?(?<!\\)),(.*)'  
    $gname = ""  
    Get-Content $ldiffile |  
        ForEach-Object {  
            [array]$p = $_ -split ": ", 2  
            if ($p[0] -eq 'dn'){  
                $gname = $p[1] -replace $regex1,'$1'  
            }  
            elseif($p[0] -eq 'uniquemember'){  
                [PSCustomObject]@{  
                    UID = $p[1] -replace $regex2,'$1'  
                    GNAME = $gname  
                }  
            }  
        } | Export-Csv $destination -NoTypeInformation  
    

  2. Satyajit Rout 0 Reputation points
    2023-01-31T15:51:10.2466667+00:00

    Hi Rich Matheisan,

    Will this script work vice-versa.

    My requirement is to prepare a script to convert csv data into ldif format.

    Please help me with the PowerShell script.

    Best Regards,

    Satyajit