我正在尝试使用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)}更多推荐
发布评论