How to remove two digits at the end of a numerical ID?

This topic contains 6 replies, has 5 voices, and was last updated by Profile photo of I Am Sir Ask Alot I Am Sir Ask Alot 11 months, 3 weeks ago.

  • Author
  • #31758
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot

    My Manager has tasked me with creating an automated solution that reads a CSV file column that contains user IDs and will remove unneeded two digits at the end of the User ID and then add this ID to the email section of the user's AD profile. These two digits are always zeros. So for instance, John Smith could have a User ID of 12345600 and I need a way of removing those last two zeros using PowerShell. Also, the User IDs may be different lengths.

    Any help on this is much appreciated.

    Thank you

  • #31759
    Profile photo of Wilfredo Perez
    Wilfredo Perez

    Did you attempt to write a script first?

  • #31761
    Profile photo of Paul Johnston
    Paul Johnston

    I'm sure there are other ways to do it but provided the CSV you're importing contains the users' SamAccountName or another attribute value accepted by Set-ADUser, this should work:

    $Users = Import-Csv C:\Input.csv
    foreach ($User in $Users) {
        $UpdatedID = $User.EmployeeID.TrimEnd('00')
        Set-ADUser -Identity $User.SamAccountName -EMailAddress $UpdatedID

    You may need to replace 'EmployeeID' and 'SamAccountName' with the column titles from your CSV file.

  • #31763
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot

    Yes, I already have a script that I wrote, but couldn't recall the method used to remove characters at the end of a string.

    Thanks Paul, Trim is indeed it.

    Appreciate your help.

    BTW, how do you add two characters at the end of a string?

    I know there is not an Insertend method.

    Also, there may not be two zeros always at the end of the ID. So is there a way to dynamically instruct PowerShell to remove just the last two digits without telling it what the digits actually are?

    Thanks again

  • #31764
    Profile photo of Mark Hammonds
    Mark Hammonds

    $variable.trimend(($variable[-2] + $variable[-1])) looks funny but without further info that's what I have.

    I know it's not elegant but this will trim any characters [-1] means the last character in the string

  • #31768
    Profile photo of Curtis Smith
    Curtis Smith

    Here's how I would do it.

    $variable = "asfsafd"
  • #31769
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot

    Ahhhh yeah, "Substring" – that's right. I totally forgot about that. Man it's been a while since I have actually performed any string manipulation.

    I'm reading this Scripting Guys article to shake out the cobwebs and I probably should have done that before dropping my question here. Anyway, thanks Curtis, Mark, and Paul.

    I appreciate all your help on this.

    "The String's the Thing"

You must be logged in to reply to this topic.