Open file, find string in a line and replace a string in a previous line

Hello guys,

there is a sample data file

Session 1: {21AD8B68-2A42-459e-BD29-F082F47E71B2}
Started: 06-24-2015 11:00
NDS Tree: TEST_TREE
AD Server: dc01.adatum.com
O=BRANCH/OU=BRANCH_CITY1/CN=user1
User
CN=user1,OU=BRANCH_CITY1,OU=ADATUM,DC=adatum,DC=com
user
O=BRANCH/OU=BRANCH_CITY1/CN=EVERYONE1
Group
CN=EVERYONE1,OU=BRANCH_CITY1,OU=ADATUM,DC=adatum,DC=com
group
O=BRANCH/OU=BRANCH_CITY2/CN=user2
User
CN=user2,OU=BRANCH_CITY2,OU=ADATUM,DC=adatum,DC=com
user
O=BRANCH/OU=BRANCH_CITY2/CN=EVERYONE2
Group
CN=EVERYONE2,OU=BRANCH_CITY2,OU=ADATUM,DC=adatum,DC=com
group

I would like to find a line that contains a string "group" (case sensitive) or "user" (case sensitive). If there will be a match, a line before should be changed like this:

if "user" change a line before to CN=<...>,OU=ADATUM,DC=adatum,DC=com

if "group" change a line before to CN=<...>,OU=GROUPS,OU=ADATUM,DC=adatum,DC=com


Of course, an output is a data file that contains all changes.

Any idea?

Many thanks in advance,

R.



  • Edited by RuNCo 23 hours 37 minutes ago
June 25th, 2015 3:33am

You forgot to post your script.

Free Windows Admin Tool Kit Click here and download it now
June 25th, 2015 4:07am

Hi RuNCo

You could use those lines to get an idea how to achieve this:

$Content = Get-Content C:\temp\Log.txt
$CMatches = $Content | Select-String -Pattern "^user" -CaseSensitive
foreach($CMatch in $CMatches)
    {
    $LineNumber = $CMatch.LineNumber -2
    $ToReplace=$Content | Select -Index $LineNumber
    $Content = $Content.Replace($ToReplace,"CN=<...>,OU=ADATUM,DC=adatum,DC=com")
    }
$Content | Out-File C:\temp\NewLog.txt

Cheers

June 25th, 2015 4:23am

Here is a different approach:

$content = Get-Content -Path C:\Sample.txt
$changes = @()

for ($i=0;$i -lt $content.Count;$i++) {
    if ($content[$i] -ceq 'user') {
        $newDN = ($content[$i-1] -split ',')[0], 'OU=ADATUM,DC=adatum,DC=com' -join ','
        $oldDN = $content[$i-1]
        $content[$i-1] = $newDN
        $changes += [pscustomobject]@{Before=$oldDN;After=$newDN}
    }
    if ($content[$i] -ceq 'group') {
        $newDN = ($content[$i-1] -split ',')[0], 'OU=GROUPS,OU=ADATUM,DC=adatum,DC=com' -join ','
        $oldDN = $content[$i-1]
        $content[$i-1] = $newDN
        $changes += [pscustomobject]@{Before=$oldDN;After=$newDN}
    }
}

$content | Out-File -FilePath C:\Sample.txt
$changes

  • Marked as answer by RuNCo 22 hours 35 minutes ago
Free Windows Admin Tool Kit Click here and download it now
June 25th, 2015 4:25am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics