Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Get number from string

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
}
like image 523
Jose Ortiz Avatar asked May 16 '14 14:05

Jose Ortiz


People also ask

How do I convert a string to a number in PowerShell?

Use [int] to Convert String to Integer in PowerShell The data type of $a is an integer . But when you enclose the value with " " , the data type will become string . To convert such string data type to integer, you can use [int] as shown below.

How do I get line numbers in PowerShell?

To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

Is Numeric in PowerShell?

There are actually three numeric types that Windows PowerShell uses: Decimal types. Integral types. Floating-point types.


1 Answers

For readability reasons (which I sometimes find difficult with regexp) I would prefer this solution:

'john123456smith' -replace "[^0-9]" , ''

123456

Replace everything which is not a number, [^0-9], with nothing, ''. This does not involve the $1 syntax (the string matched by the regex)

like image 160
Gunnar Storebø Avatar answered Oct 18 '22 21:10

Gunnar Storebø