select second or third object / element

前端 未结 4 1938
我寻月下人不归
我寻月下人不归 2021-01-02 05:51

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-Child         


        
4条回答
  •  醉话见心
    2021-01-02 06:07

    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

    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

    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.

提交回复
热议问题