Powershell 从字符串中获取数字

标签 powershell replace

大家好,我正在尝试使用 powershell 从用户 ID 中获取号码

我们使用的格式是名字的第一个字母、姓氏的前四个字母和学生 ID,因此一个名为 John Smith 且 ID# 123456 的学生将是 jsmit123456
如果用户的名字少于 4 个字母,我会遇到问题。
所以使用子字符串会给那些 id 的错误

我试过选择字符串、-匹配、修剪、修剪开始、修剪

到目前为止,这是我的代码

$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
}

最佳答案

使用正则表达式很简单:

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

 123456

\D+ = 所有非数字,\d+ = 后面的所有数字。
 $studentid = $object.SAMAccountName -replace '\D+(\d+)','$1'

关于Powershell 从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697408/

相关文章:

internet-explorer - 使用 Powershell 自动化 IE 确认提示

c# - 用控件替换字符串中的 xml 标记

python - 如何在Python中删除重复的短语?

java - 替换所有特殊字符

powershell - 在 powershell 中一次查看 MSMQ 一条消息

powershell - F# 将 Powershell 脚本作为目标运行

带有标题到哈希表的 Powershell CSV

string - 字符串-match的PowerShell问题

php - 从大型 mysql 数据库中的字段中删除奇怪的字符

c# - 在没有内存泄漏的情况下替换大字符串中的文本