从Powershell中的列表中选择最后一项

Nim*_*jox 13 sorting powershell list

我正在尝试使用这行代码映射驱动器号,这将为我提供从d到z可用的驱动器列表.

ls function:[d-z]: -n|?{!(test-path $_)}
Run Code Online (Sandbox Code Playgroud)

我想从列表中选出最后一个字母,而不是随机字母.我该怎么做呢?Powershell的新手,感谢您的帮助.

Joe*_*oey 25

您可以Select-Object -Last 1在该管道的末尾使用.


小智 19

您可以从列表的最后面开始,然后向上。

最后一项:$array[-1] 倒数第二项:$array[-2] 依此类推。


小智 5

如果你想要更冗长,但(在我看来)可读性改进版本:

# Get all drives which are used (unavailable)
# Filter for the "Name" property ==> Drive letter
$Drives = (Get-PSDrive -PSProvider FileSystem).Name

# Create an array of D to Z
# Haven't found a more elegant version...
$Letters = [char[]]([char]'D'..[char]'Z')

# Filter out, which $Letters are not in $Drives (<=)
# Again, filter for their letter
$Available = (Compare-Object -ReferenceObject $Letters -DifferenceObject $Drives | Where {$_.SideIndicator -eq "<="}).InputObject

# Get the last letter
$LastLetter = $Available[-1]
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这样:`$ letters = 69..90 | %{[char] $ _}` (2认同)
  • @CB:使用`[char []](69..90)`可以轻松完成.无需将管道拖动到简单的转换中. (2认同)