Get last element of pipeline in powershell

被刻印的时光 ゝ 提交于 2019-11-29 13:03:19

问题


This might be weird, but stay with me. I want to get only the last element of a piped result to be assigned to a varaiable. I know how I would do this in "regular" code of course, but since this must be a one-liner.

More specifically, I'm interested in getting the file extension when getting the result from an FTP request ListDirectoryDetails.

Since this is done within a string expansion, I can't figure out the proper code.

Currently I'm getting the last 3 hars, but that is real nasty.

New-Object PSObject -Property @{
LastWriteTime = [DateTime]::ParseExact($tempDate, "MMM dd HH:mm",[System.Globalization.CultureInfo]::InvariantCulture)
Type = $(if([int]$tempSize -eq 0) { "Directory" } else { $tempName.SubString($tempName.length-3,3) })
Name = $tempName
Size = [int]$tempSize
}

My idea was doing something similar to

    $tempName.Split(".") | ? {$_ -eq $input[$input.Length-1]}

that is, iterate over all, but only take out where the element I'm looking at is the last one of the input-array.

What am I missing ?


回答1:


A few ways to do this:

$name = 'c:\temp\aaa.bbb.ccc'

# way 1
$name.Split('.') | Select-Object -Last 1

# way 2
[System.IO.Path]::GetExtension($name)

# or if the dot is not needed
[System.IO.Path]::GetExtension($name).TrimStart('.')



回答2:


In general, getting the last element in the pipeline would be done using Select -Last 1 as Roman suggests above. However, an alternate and easier way to do this if the input is a simple array is to use array slicing e.g.:

PS> $name = "c:\temp\aaa.bbb.txt"
PS> $name.Split('.')[-1]
txt

Was your intent to get the file's extension or basename? Because it seems that the Type property already contains the extension for the filename.



来源:https://stackoverflow.com/questions/4546567/get-last-element-of-pipeline-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!