Powershell Get number from string

powershell, replace

Solution

This is simple to do with a regex:

 ('jsmit123456') -replace '\D+(\d+)','$1'

 123456

\D+ = all the non-digits, \d+ = all the digits that follow.

 $studentid = $object.SAMAccountName -replace '\D+(\d+)','$1'

Problem

Hi all I am trying to get the number from a users id using powershell The format we use is the first letter of the first name, first four letters of the last name and studentid so a student with the name John Smith with Id# 123456 would be jsmit123456 the problem I get if the user has less than 4 letters in their name. so using substring would give and error for those id's I tried select-string, -match, trim, trimstart, trimend here is my code so far ``` $name = Get-ADUser -SearchBase "OU=A,DC=B,DC=C,DC=edu" -Filter {Created -ge $checktime} |Select-Object SAMAccountName foreach($object in $name){ $object $studentid = $object.SAMAccountName.Substring(5,6) $studentid } ```

Original source