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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18018892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:03:30  来源:igfitidea点击:

Pick last item from list in Powershell

listsortingpowershell

提问by Nimjox

I'm trying to map a drive letter using this line of code which will give me a list of drives available from d to z.

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

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

I'd like to then pick the last letter, not random, from the list. How would I go about doing that? New to Powershell, thanks for the help.

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

回答by Joey

You can use Select-Object -Last 1at the end of that pipeline.

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

回答by Dreami

If you look for a much more verbose, but (in my opinion) readable-improved version:

如果您寻找更冗长但(在我看来)可读性改进的版本:

# 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]

回答by Dave Sexton

Try this:

尝试这个:

ls function:[d-z]: -n|?{!(test-path $_)} | Select-Object -Last 1

回答by neontapir

Another option that doesn't require trying all paths from D-Z is to parse Get-Psdrive. Here's an example:

另一个不需要从 DZ 尝试所有路径的选项是解析Get-Psdrive. 下面是一个例子:

$lettersInUse = Get-Psdrive | ? { $_.Name.Length -eq 1 } | % { $_.Name }
$lastDriveLetter = [Char]'Z'
while ($lettersInUse -contains $lastDriveLetter) {
  $lastDriveLetter = [Char]($lastDriveLetter - 1)
}
$lastDriveLetter

回答by Ashu

  1. In case of Array
    $newArray = @(git tag --list)
    $lastmember = $newArray[$newArray.Count – 1]

  2. In case you have list
    $newArray | Select-Object -Last 1

  1. 在数组的情况下
    $newArray = @(git tag --list)
    $lastmember = $newArray[$newArray.Count – 1]

  2. 如果您有列表
    $newArray | 选择对象 - 最后 1