Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick last item from list in Powershell

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.

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.

like image 371
Nimjox Avatar asked Aug 02 '13 14:08

Nimjox


2 Answers

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

like image 51
Joey Avatar answered Sep 22 '22 17:09

Joey


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]
like image 35
Dreami Avatar answered Sep 22 '22 17:09

Dreami