Home > Back-end >  Is it possible to alter part of a variable based on its value?
Is it possible to alter part of a variable based on its value?

Time:03-19

I have a script that grabs a list of AD usernames for members of a student group and allocates those as an array of $students

Later the script will need to take those usernames and input them into a URL

$students = Get-ADGroupMember -Identity "GG_LHS All Students" | Select-Object -ExpandProperty SamAccountName | Sort-Object SamAccountName

foreach ($student in $students)
{
    foreach ($OneDriveAdmin in $OneDriveAdmins)
Set-SPOUser -Site https://mydomain-my.sharepoint.com/personal/$($student)_mydomain_co_uk

In the cases where we have duplicate usernames, our naming scheme adds increments in the format of .1 and .2, but I need to change the ".1" to a "_1" to work in the URL.

My initial thinking is an IF statement during the $students declaration IF SamAccountName is like '.1' replace '.1' with '_1'

Is this possible to do via powershell?

CodePudding user response:

To offer a streamlined alternative to Santiago Squarzon's helpful answer, using the (also regex-based)
-replace operator:

# Sample student account names
$students = 'jdoe.1', 'jsixpack', 'jroe.2'

# Transform all names, if necessary, and loop over them.
foreach ($student in $students -replace '\.(?=\d $)', '_') {
  $student
}

Regex notes: \. matches a verbatim ., and (?=...) is a look-ahead assertion that matches one or more ( ) digits (\d) at the end ($) of the string. What the look-ahead assertion matches doesn't become part of the overall match, so it is sufficient to replace only the . char.

Output:

jdoe_1
jsixpack
jroe_2

Note:

  • -replace - like -match accepts an array as its LHS, in which case the operation is performed on each element, and a (usually transformed) new array is returned.

  • If the regex on the RHS in a given replacement operation doesn't match, the input string is passed through (returned as-is), so it is safe to attempt replacement on strings that don't match the pattern of interest.

CodePudding user response:

You could add this check in your loop, if student matches a dot followed by any amount of digits (\.(\d )), replace for the same digits but prepending and underscore instead (-replace $Matches[0], "_$($Matches[1])"):

foreach($student in $students) {
    if($student -match '\.(\d )$') {
        $student = $student -replace $Matches[0], "_$($Matches[1])"
    }

    # rest of your code here
}

See https://regex101.com/r/fZAOur/1 for more info.

  • Related