在Powershell中为CollectionView.CustomSort创建自定义排序器

时间:2017-06-06 14:49:31

标签: powershell sorting icomparer

我对Powershell来说是个新手,并且已经在地球的两端寻找解决方案,但我似乎无法找到任何东西。我希望它仍然可行。

我正在尝试按字符串格式按日期排序CollectionView。在我的自定义排序器中,我想将日期字符串(M / dd / yyyy)转换为Date对象,并使Comparer按日期排序。我的CollectionView填充如下:

$stuff = [System.Collections.ObjectModel.ObservableCollection[System.Object]](ImportClixml -Path $path)
$view = [System.Windows.Data.CollectionView]([System.Windows.Data.CollectionViewSource]::GetDefaultView($stuff))

XML数据中包含PropertiesString值的Boolean数据。我尝试排序的日期值是StringCollectionView绑定到DataGrid,如此:$myDataGrid.ItemsSource = $myCollectionView 我可以制作一个排序功能,并以某种方式指向它吗?

function customSorter{ #Do Stuff }
$myCollectionView.CustomSort = customSorter

CustomSort属性接收System.Collections.IComparer个对象。我不知道如何处理这个问题。我更愿意将它全部保存在powershell 4中,而不是导入C#代码或类似的东西。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以将字符串日期格式化为日期时间对象

例如,yyyy-MM-dd格式很容易排序。

如果您想转换字符串日期,可以使用:

$timeinfo = '6/06/2017'
$template = 'M/dd/yyyy'
$newDate = Get-Date([DateTime]::ParseExact($timeinfo, $template, $null)) -Format "yyyy-MM-dd"

结果是:2017-06-06