Get last element of pipeline in powershell

29,722

Solution 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('.')

Solution 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.

Share:
29,722
dozacinc
Author by

dozacinc

Updated on December 31, 2020

Comments

  • dozacinc
    dozacinc over 3 years

    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 ?