【问题标题】:Powershell - Is there any way to sort unique objects in ForEach-Object?Powershell - 有没有办法对 ForEach-Object 中的唯一对象进行排序?
【发布时间】:2022-01-19 12:15:39
【问题描述】:

我有一个数组,我需要对唯一值和重复值进行排序,并将其显示给Show-ListView。我是制作 PowerShell 脚本的初学者,尤其是 Sitecore,所以我的代码看起来很糟糕,但对我来说很糟糕。

这是目前的代码:

@($rootItem) + @($rootItem.Axes.GetDescendants() | Initialize-Item) | 
    ForEach-Object {
        $currentItem = $_
        Get-ItemField -Item $currentItem -ReturnType Field -Name "*" `
            | ForEach-Object{
                $NewValue = $value.Split(",")
                ForEach($i in $NewValue) {
                if($PSItem.Value -match $i -and $PSItem.Name.Contains("Tags")){
                    [pscustomobject]@{
                        "Name"=$currentItem.DisplayName
                        "ItemId"=$currentItem.ID
                        "FieldName"=$_.Name
                        "ItemPath" = Get-MediaUrl($currentItem)
                    }
Copy-Item -Path $currentItem.ItemPath -Destination $folderToMove.Paths.FullPath;
                }
                }
                
            } 
} | Show-ListView

$rootItem 只是这些项目所在的文件夹(sitecore/Media Library/Images)。现在我需要将这些项目复制到另一个文件夹。这实际上不是问题,因为在 Sitecore 中它不会复制重复值,但在 Show-ListView 中会显示它们。

为了描述我遇到的问题,我基本上想获得具有某些标签图像。当你输入一个标签时,一切都很好,但是当我输入一组标签时,例如stackoverflow,sitecore,它会显示一个具有这两个标签的项目,两次。

我有什么办法排序 ForEach-Object。我现在有Sort-Object -Unique,但我不知道这是否对我有帮助。

【问题讨论】:

  • sort 将接受管道输入。
  • 将最后一行从} | Show-ListView改为} |Sort-Object -Unique ItemID | Show-ListView
  • @MathiasR.Jessen 非常感谢!成功了!

标签: powershell sitecore powershell-4.0


【解决方案1】:

就像@MathiasR.Jessen 在 cmets 中所说,基本上我必须在代码末尾添加|Sort-Object -Unique ItemID | Show-ListView

现在的工作代码如下所示:

@($rootItem) + @($rootItem.Axes.GetDescendants() | Initialize-Item) | 
    ForEach-Object {
        $currentItem = $_
        Get-ItemField -Item $currentItem -ReturnType Field -Name "*" `
            | ForEach-Object{
                $NewValue = $value.Split(",")
                ForEach($i in $NewValue) {
                if($PSItem.Value -match $i -and $PSItem.Name.Contains("Tags")){
                    [pscustomobject]@{
                        "Name"=$currentItem.DisplayName
                        "ItemId"=$currentItem.ID
                        "FieldName"=$_.Name
                        "ItemPath" = Get-MediaUrl($currentItem)
                    }
Copy-Item -Path $currentItem.ItemPath -Destination $folderToMove.Paths.FullPath;
                }
                }
                
            } 
} | Sort-Object -Unique ItemID | Show-ListView

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2011-09-16
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多