Powershell Sort

编程入门 行业动态 更新时间:2024-10-23 19:18:24
Powershell Sort-Object by [DateTime] :: ParseExact(Powershell Sort-Object by [DateTime]::ParseExact)

我正在尝试使用PowerShell按日期对控制台程序返回的行进行排序。

日期以MM / dd / yyyy格式格式化,因此必须将它们转换为DateTime对象以采用可排序的格式。

要解析日期,我使用:

$dates = %{ "10/24/2010", "02/03/2010" } $dates | %{ [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null) }

这会将日期解析为System.DateTime对象并显示其默认的ToString()表示,但它也会在开头显示另一个空行。

现在,如果我尝试使用Sort-Object对日期进行排序,我会收到一条错误消息,我猜错误来自额外的空白行:

$sortedDates = $dates | Sort-Object [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)

错误信息:

“Sort-Object:找不到接受参数'System.Object []'的位置参数。”

额外的空白行是从哪里来的? 我是在做错什么来解析日期,还是对它们进行排序?

I'm trying to sort the lines returned by a console program by date, using PowerShell.

The dates are formated in MM/dd/yyyy format, so they have to be converted to DateTime objects to be in a sortable format.

To parse the dates, I use:

$dates = %{ "10/24/2010", "02/03/2010" } $dates | %{ [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null) }

This parses the dates into System.DateTime objects and displays their default ToString() representation, but it also shows an additional blank line at the beginning.

Now, if I try to sort the dates with Sort-Object, I get an error message, and I guess the error comes from the additional blank line:

$sortedDates = $dates | Sort-Object [System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)

Error message:

"Sort-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'."

Where is the extra blank line coming from? Am I doing something wrong to parse the dates, or to sort them?

最满意答案

我认为部分问题出在第一行。

%{}表示foreach-object {}。

我认为你的意思是@(,)。 你甚至不需要@()。

$dates= "10/24/2010", "02/03/2010"

工作正常。 要按“派生字段”排序,请使用scriptblock。

$sortedDates = $dates | Sort-Object {[System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)}

I think part of the problem is in the first line.

%{ } means foreach-object { }.

I think you meant @( , ). You don't really even need the @( ).

$dates= "10/24/2010", "02/03/2010"

works fine. To sort by a "derived field", use a scriptblock.

$sortedDates = $dates | Sort-Object {[System.DateTime]::ParseExact($_, "MM/dd/yyyy", $null)}

更多推荐

本文发布于:2023-07-16 12:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Powershell   Sort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!