选择第二个或第三个对象/元素 [英] select second or third object / element

查看:55
本文介绍了选择第二个或第三个对象/元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 PowerShell 脚本中选择 Get-ChildItem 语句的第二个/第三个/第四个对象.这给了我第一个:

I want to select the second/third/forth object of a Get-ChildItem statement in my PowerShell script. This gives me the first:

$first = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -First 1

这给了我前三个:

$latest = Get-ChildItem -Path $dir |
          Sort-Object CreationTime -Descending |
          Select-Object -First 3

我想要第二个、第三个或第四个.(不是前两个等等).

I would like to get the second, or the third, or the fourth. (NOT the first two and so on).

有办法吗?

推荐答案

对于选择第n个元素跳过前n-1个元素:

For selecting the n-th element skip over the first n-1 elements:

$third = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -Skip 2 |
         Select-Object -First 1

或者选择第一个 n 然后选择最后一个元素:

or select the first n and then of those the last element:

$third = Get-ChildItem -Path $dir |
         Sort-Object CreationTime -Descending |
         Select-Object -First 3 |
         Select-Object -Last 1

但是请注意,如果输入的元素少于 n 个,这两种方法将产生不同的结果.在这种情况下,第一种方法将返回 $null,而第二种方法将返回最后一个可用元素.根据您的要求,您可能需要选择其中之一.

Beware, though, that the two approaches will yield different results if the input has less than n elements. The first approach would return $null in that scenario, whereas the second approach would return the last available element. Depending on your requirements you may need to choose one or the other.

这篇关于选择第二个或第三个对象/元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆