Maca
Maca

Reputation: 1

PowerShell - open a file, find a string in a line and replace a string in a previous line

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,
M.

Upvotes: 0

Views: 109

Answers (2)

arco444
arco444

Reputation: 22881

Something like this should do the trick:

$c = Get-Content .\file_name.txt

for ($i = 0; $i -lt $c.length; $i++) {
  if ($c[$i] -cmatch "^group" ) { 
    $c[$i-1] = "CN=<...>,OU=ADATUM,DC=adatum,DC=com"
  }
  elseif ($c[$i] -cmatch "^user") {
    $c[$i-1] = "CN=<...>,OU=GROUPS,OU=ADATUM,DC=adatum,DC=com"
  }
}

$c | Out-File .\new_file.txt

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

The easiest way to accomplish this is probably by using a regular for loop to keep track of line numbers - if line $n matches "user", replace the string in line $n-1.

To do a case-sensitive regex, use -cmatch (notice the c prefix). In the example below I've used a named capture group ((?<name>pattern)) to match and capture either user or group.

The last part, adding a new path to the existing CN=<...> part can be accomplished with the -split command and a lookbehind to avoid messing up escaped commas in the CN value:

# Read file, line by line
$SampleFile = @(Get-Content C:\path\to\data.txt)
# Loop over the text by line numbers
for($i=0;$i -lt $SampleFile.Count;$i++){
    # Test if the line matches
    if(![string]::IsNullOrWhiteSpace($SampleFile[$i]) -and $SampleFile[$i].Trim() -cmatch "(?<type>^group|user$)"){
        # If so, use the match to determine the DN suffix
        switch($Matches["type"]){
            "group" { $SampleFile[$i-1] = "{0},OU=GROUPS,OU=ADATUM,DC=adatum,DC=com" -f ($SampleFile[$i-1] -split "(?<!\\),")[0] }
            "user"  { $SampleFile[$i-1] = "{0},OU=ADATUM,DC=adatum,DC=com" -f ($SampleFile[$i-1] -split "(?<!\\),")[0] }
        }
    }
}
$SampleFile | Out-File C:\path\to\output.txt -Force 

Upvotes: 2

Related Questions