在powershell中获取管道的最后一个元素
这可能很奇怪,但请留在我身边。 我只想将管道结果的最后一个元素分配给变量。 当然,我知道如何在“常规”代码中执行此操作,但因为这必须是一行代码。
更具体地说,我有兴趣在从 FTP 请求 ListDirectoryDetails
获取结果时获取文件扩展名。
由于这是在字符串扩展中完成的,因此我无法找出正确的代码。
目前我已经得到了最后 3 个小时,但这真的很糟糕。
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
}
我的想法是做类似的事情
$tempName.Split(".") | ? {$_ -eq $input[$input.Length-1]}
,即迭代所有元素,但只取出我正在查看的元素是输入数组的最后一个元素。
我缺少什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种方法可以做到这一点:
A few ways to do this:
一般来说,获取管道中的最后一个元素将使用
Select -Last 1
完成,如 Roman 上面建议的那样。但是,如果输入是简单数组,则另一种更简单的方法是使用数组切片,例如:您是否打算获取文件的扩展名或基本名称?因为
Type
属性似乎已经包含文件名的扩展名。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.: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.