我希望能够在PowerShell脚本中添加功能,以便在foreach循环中向前移动一个点或向后移动一个点。在循环遍历foreach语句时,是否可以向前和向后移动,或者确定当前项位于数组中的哪个点?
编辑-数组中的项是文件,而不是数字。
发布于 2020-04-20 18:45:16
是的-这叫for循环!
对于我们可以索引到的数据结构(数组、列表等),可以很容易地将foreach循环语句转换为for循环语句,如下所示:
# This foreach loop statement
foreach($item in $array){
Do-Something $item
}
# ... is functionally identical to this for loop statement
for($i = 0; $i -gt $array.Length; $i++){
$item = $array[$i]
Do-Something $item
}由于我们可以直接访问for循环中的当前索引(通过for),我们现在可以使用它作为偏移量来“查看”数组中的那个位置:
$array = @(1,2,3,4)
for($i = 0; $i -lt $array.Length;$i++)
{
$item = $array[$i]
if($i -gt 0){
# If our index position $i is greater than zero,
# then there must be _at least_ 1 item "behind" us
$behind = $array[$i - 1]
}
if($i -lt ($array.Length - 1)){
# Not at end of array, we can also "look ahead"
$ahead = $array[$i + 1]
}
}在检查是否使用$i值大于$array.Length (这将导致$null)或小于0 (在这种情况下,PowerShell将开始向后读取数组)时,请小心!
https://stackoverflow.com/questions/61329481
复制相似问题