问题描述
大家好,我正在尝试使用 powershell 从用户 ID 中获取号码
Hi all I am trying to get the number from a users id using powershell
我们使用的格式是名字的第一个字母、姓氏的前四个字母和 studentid 所以一个名为 John Smith 和 Id# 123456 的学生将是 jsmit123456如果用户的名字少于 4 个字母,我会遇到问题.所以使用子字符串会给那些 id 带来错误
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 jsmit123456the 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
我试过 select-string、-match、trim、trimstart、trimend
I tried select-string, -match, trim, trimstart, trimend
这是我目前的代码
$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
}
推荐答案
使用正则表达式很简单:
This is simple to do with a regex:
('jsmit123456') -replace '\D+(\d+)','$1'
123456
\D+ = 所有非数字,\d+ = 后面的所有数字.
\D+ = all the non-digits, \d+ = all the digits that follow.
$studentid = $object.SAMAccountName -replace '\D+(\d+)','$1'
这篇关于Powershell 从字符串中获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!