Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to alter part of a variable based on its value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading