-1

I try to update users AD accounts properties with values imported from csv file. The problem is that some of the properties like department allow strings of length of max length 64 that is less than provided in the file which can be up to 110.

I have found and adopted solution provided by TroyBramley in this thread - How to replace multiple strings in a file using PowerShell (thank You Troy).

It works fine but... Well. After all replaces have place the text is less meaningful than originally.

For example, original text First Department of something1 something2 something3 something4 would result in 1st Dept of sth1 sth2 sth3 sth4

I'd like to have control over the process so I can stop it when the length of the string drops just under the limit alowed by AD property.

By the way. I'd like to have a choice which replacement takes first, second and so on, too.

I put elements in a hashtable alphabetically but it seems that they are not processed this way. I can't figure out the pattern.

I can see the resolution by replacing strings one by one, controlling length after each replacement. But with almost 70 strings it leds to huge portion of code. Maybe there is simpler way?

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
KrzychG
  • 47
  • 10
  • 1
    So what you need is to create your list of replaces. Do it as an array or arraylist not a hash since you can put them in the order that you want and order will be honored then. Go through the list and us an if statement to only do each replace if the length of the string is still greater than 64. Alternatively you could use a do-until or a while block. Write some concrete code then post back here when you have specific problems with the code that you have written. – EBGreen Jun 26 '18 at 12:49

1 Answers1

2

You can iterate the replacement list until the string reaches the MaxLength defined.

## Q:\Test\2018\06\26\SO_51042611.ps1

$Original = "First Department of something1 something2 something3 something4"

$list = New-Object System.Collections.Specialized.OrderedDictionary
$list.Add("First","1st")
$list.Add("Department","Dept")
$list.Add("something1","sth1")
$list.Add("something2","sth2")
$list.Add("something3","sth3")
$list.Add("something4","sth4")

$MaxLength = 40

ForEach ($Item in $list.GetEnumerator()){
    $Original = $Original -Replace $Item.Key,$Item.Value
    If ($Original.Length -le $MaxLength){Break}
}

"{0}: {1}" -f $Original.Length,$Original

Sample output with $MaxLength set to 40

37: 1st Dept of sth1 sth2 sth3 something4