我目前正在访问一个API并解析一个XML,以便从3000+系统中获取计算机Im。我获取in并将它们存储在var $computers中,我只需要最后一个数字,这样我就可以使用开关将它们放入适当的组中。这是我所拥有的
foreach($ID in $Computers){
Switch ($ID){
0{write-host "0"}
1{write-host "1"}
2{write-host "2"}
3{write-host "3"}
4{write-host "4"}
5{write-host "5"}
6{write-host "6"}
7{write-host "7"}
8{write-host "8"}
9{write-host "9"}
}
}
由于隐私原因,我修改了{}中的实际命令(我使用的是特定于公司的URL)。ID数字以"1“或"11”的格式出现,一直到"1111“。基本上,一行数字,最多4个数字。都是随机的,而且看上去没有什么特别的顺序。我已经在谷歌上搜索了几个小时,想不出如何从ID中获取最后一个号码,任何帮助都将是非常感谢的。
发布于 2016-07-02 02:51:57
简单回答:[-1]
从字符串中提取最后一个字符。
$computers = '111', '23', '1567'
foreach ($ID in $computers) {
switch ($ID[-1]) {
0 { write-host -ForegroundColor Cyan "0" }
1 { write-host -ForegroundColor Cyan "1" }
2 { write-host -ForegroundColor Cyan "2" }
3 { write-host -ForegroundColor Cyan "3" }
4 { write-host -ForegroundColor Cyan "4" }
5 { write-host -ForegroundColor Cyan "5" }
6 { write-host -ForegroundColor Cyan "6" }
7 { write-host -ForegroundColor Cyan "7" }
8 { write-host -ForegroundColor Cyan "8" }
9 { write-host -ForegroundColor Cyan "9" }
}
}
要么你花了几个小时在谷歌上搜索,却没有发现-> --在一个月的午餐打字书或教程中,你迫切需要一个PowerShell。
或者,您有一些奇怪的格式ID,这是做不到的。Regex很有趣,另一种方法可能是:
$computers = '111', '23', '1567'
switch -regex ($computers) {
'.*0$' { write-host -ForegroundColor Cyan "0" }
'.*1$' { write-host -ForegroundColor Cyan "1" }
'.*2$' { write-host -ForegroundColor Cyan "2" }
'.*3$' { write-host -ForegroundColor Cyan "3" }
'.*4$' { write-host -ForegroundColor Cyan "4" }
'.*5$' { write-host -ForegroundColor Cyan "5" }
'.*6$' { write-host -ForegroundColor Cyan "6" }
'.*7$' { write-host -ForegroundColor Cyan "7" }
'.*8$' { write-host -ForegroundColor Cyan "8" }
'.*9$' { write-host -ForegroundColor Cyan "9" }
}
示例输出:
Switch语句将隐式遍历数组,调整regex以适应ID格式。
发布于 2016-07-21 21:13:18
根据厄里斯的评论,这是对我有用的东西。我自己没有提到和理解的问题是,我存储在$ID var中的XML没有我现在所需要的数据。我需要将其解析为$ID.id,以便从XML中获取ID元素。我的坏家伙们!!
foreach($ID in $Computers){
$Lastdigit = $ID.id % 10
Switch ($Lastdigit){
0{write-host "0"}
1{write-host "1"}
2{write-host "2"}
3{write-host "3"}
4{write-host "4"}
5{write-host "5"}
6{write-host "6"}
7{write-host "7"}
8{write-host "8"}
9{write-host "9"}
}
https://stackoverflow.com/questions/38155208
复制相似问题