英文:
Extract numbers from Bios-Serial and make it four-digit
问题
需要从使用以下命令获取的 BIOS 序列号字符串中提取数字:
在 [tag:cmd] 中使用 wmic bios get serialnumber
或在 [tag:powershell] 中使用 Get-WmiObject win32_bios | select Serialnumber
。
为了使整个过程稍微复杂一些,结果必须限制为四位数字。此外,结果必须使用序列号的最右侧数字。
例如:A1G2S3W4B5 -> 1**2345**
如果序列号不包含4个数字,缺少的数字将用零填充。
您有关于如何在命令行或PowerShell中实现这一点的任何想法或解决方案吗?
我的最基本的想法是将序列查询的结果传输到findstr
或类似的工具,并对数字进行排序...
提前感谢您的帮助,
Chris
英文:
I need to get extracted the numbers from the bios serial string which I get using by:
wmic bios get serialnumber
in [tag:cmd] or Get-WmiObject win32_bios | select Serialnumber
in [tag:powershell].
Making the whole story a little more complicated the result has to be limited to four digits. In addition the result must use the rightmost digits of the serial.
eg.: A1G2S3W4B5 -> 1**2345**
If the serial does not contain 4 numbers the missing digits shall be filled by zeros.
Do you have any ideas or solutions on how to achieve this in command shell or PowerShell?
My minimal basic idea is to pipe the result of the serial query to findstr
or something like that and sorting the numbers...
Thanks in advice,<br>
Chris
答案1
得分: 0
这是一种方法来做这个,首先它从字符串中移除任何非数字字符,然后移除除最后4个数字之外的所有数字(假设可能有多于4个数字),最后使用 PadLeft
添加左侧零填充。如果你希望填充在右侧,使用 $result.PadRight(4, '0')
代替:
$result = (Get-CimInstance win32_bios).SerialNumber -replace '\D' -replace '\d*(?=\d{4}$)'
$result.PadLeft(4, '0')
添加一些示例来查看它的效果:
@(
'AG0123SW4B5'
'1AG12SW4B5'
'FOOBARBAZ'
'FOO1BAR2BAZ'
) | ForEach-Object {
$result = $_ -replace '\D' -replace '\d+(?=\d{4}$)'
$result.PadLeft(4, '0')
}
这将产生以下结果:
2345
1245
0000
0012
英文:
Here is one way to do it, first it removes any non-digit char from the string, then it removes all digits except the last 4 (assuming there could be more than 4) and lastly it adds left zero-padding using .PadLeft
. If you wanted the padding to be on the right side, the use $result.PadRight(4, '0')
instead:
$result = (Get-CimInstance win32_bios).SerialNumber -replace '\D' -replace '\d*(?=\d{4}$)'
$result.PadLeft(4, '0')
Adding some examples to see how it looks:
@(
'AG0123SW4B5'
'1AG12SW4B5'
'FOOBARBAZ'
'FOO1BAR2BAZ'
) | ForEach-Object {
$result = $_ -replace '\D' -replace '\d+(?=\d{4}$)'
$result.PadLeft(4, '0')
}
This results in:
2345
1245
0000
0012
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论