在PowerShell中将字符串转换为int数组 [英] Convert string to int array in PowerShell
本文介绍了在PowerShell中将字符串转换为int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试转换一个看起来像这样的字符串,
I'm trying to convert a string that looks like this,
2,3,4,5,6,20..30
到一个整数数组.这是我目前拥有的代码:
to an array of integers. Here is the code I currently have:
[string]$a = "2,3,4,5,6,7"
[array]$b = $a.split(",")
[array]$c = foreach($number in $b) {([int]::parse($number))}
哪个有效,但不适用于 20..30 的范围.我如何让那部分工作?
Which works, but not for the range of 20..30. How do I get that part working?
推荐答案
您可以使用 Invoke-Expression
cmdlet 来解释 10..30
位,如果[int]::Parse()
方法调用失败.
You can use the Invoke-Expression
cmdlet to interpret the 10..30
bit, if the [int]::Parse()
method call fails.
这是一个完整的工作示例.
Here is a complete, working sample.
[string]$a = "2,3,4,5,6,7,10..30";
[array]$b = $a.split(",");
[array]$c = foreach($number in $b) {
try {
[int]::parse($number)
}
catch {
Invoke-Expression -Command $number;
}
}
$c;
这篇关于在PowerShell中将字符串转换为int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文