Добавьте ссылки на веб-часть Quick Links, используя PowerShell и JSON - PullRequest
0 голосов
/ 06 февраля 2020

Я пытаюсь добавить ссылки на веб-часть Quick Links на современном сайте SharePoint, для этого я использую PowerShell и JSON. Я получил веб-часть в виде файла JSON и получил к нему доступ с помощью команды Get-Content.

JSON для веб-части быстрых ссылок выглядит следующим образом:

{
        "controlType": 3,
        "id": "a9ed7796-5545-4623-a943-5be42762691d",
        "position": {
            "zoneIndex": 1,
            "sectionIndex": 1,
            "controlIndex": 1,
            "layoutIndex": 1
        },
        "webPartId": "c70391ea-0b10-4ee9-b2b4-006d3fcad0cd",
        "webPartData": {
            "id": "c70391ea-0b10-4ee9-b2b4-006d3fcad0cd",
            "instanceId": "a9ed7796-5545-4623-a943-5be42762691d",
            "title": "Quick links",
            "description": "Add links to important documents and pages.",
            "serverProcessedContent": {
                "htmlStrings": {},
                "searchablePlainTexts": {
                    "items[0].title": "Yahoo",
                    "items[1].title": "Google"
                },
                "imageSources": {
                    "items[0].rawPreviewImageUrl": "https://s.yimg.com/cv/apiv2/social/images/yahoo_default_logo.png"
                },
                "links": {
                    "baseUrl": "https://bbpocoutlook.sharepoint.com/sites/tl23",
                    "items[0].sourceItem.url": "https://yahoo.com",
                    "items[1].sourceItem.url": "https://google.com"
                },
                "componentDependencies": {
                    "layoutComponentId": "706e33c8-af37-4e7b-9d22-6e5694d92a6f"
                }
            },
            "dataVersion": "2.2",
            "properties": {
                "items": [
                    {
                        "sourceItem": {
                            "itemType": 2,
                            "fileExtension": "",
                            "progId": ""
                        },
                        "thumbnailType": 3,
                        "id": 2,
                        "description": "",
                        "altText": ""
                    },
                    {
                        "sourceItem": {
                            "itemType": 2,
                            "fileExtension": "",
                            "progId": ""
                        },
                        "thumbnailType": 3,
                        "id": 1,
                        "description": "",
                        "altText": ""
                    }
                ],
                "isMigrated": true,
                "layoutId": "List",
                "shouldShowThumbnail": true,
                "buttonLayoutOptions": {
                    "showDescription": false,
                    "buttonTreatment": 2,
                    "iconPositionType": 2,
                    "textAlignmentVertical": 2,
                    "textAlignmentHorizontal": 2,
                    "linesOfText": 2
                },
                "listLayoutOptions": {
                    "showDescription": false,
                    "showIcon": true
                },
                "waffleLayoutOptions": {
                    "iconSize": 1,
                    "onlyShowThumbnail": false
                },
                "hideWebPartWhenEmpty": true,
                "dataProviderId": "QuickLinks",
                "webId": "b5fdf80c-54ce-410f-a50d-910ea2e33250",
                "siteId": "0c8f4c9a-71e6-4fc0-8355-9b52f0a7eb3a"
            }
        },
        "emphasis": {},
        "reservedHeight": 132,
        "reservedWidth": 744,
        "addedFromPersistedData": true
    }

Как добавить новый элемент в веб-часть и добавить ссылку на него?

Например, как добавить ссылку на stackoverflow на веб-часть быстрой ссылки через PowerShell?

1 Ответ

2 голосов
/ 06 февраля 2020

Вы можете прочитать JSON и преобразовать его в объект со свойствами, используя ConvertFrom-Json. Затем вы можете добавить быструю ссылку, выполнив:

# if the json is in a file:
$json = Get-Content -Path 'TheJsonFile.json' | ConvertFrom-Json

$plainTexts = $json.webPartData.serverProcessedContent.searchablePlainTexts
$plainTexts | Add-Member -MemberType NoteProperty -Name 'items[2].title' -Value 'Stack Overflow'

$links = $json.webPartData.serverProcessedContent.links
$links | Add-Member -MemberType NoteProperty -Name 'items[2].sourceItem.url' -Value 'https://stackoverflow.com/'

Затем преобразуйте измененный объект обратно в JSON:

$json | ConvertTo-Json -Depth 5 

и, возможно, сохраните его на диск с помощью Set-Content

Примечание. PowerShell не создает «симпатичных» json. Отступ действительно ужасен. Если вы хотите, чтобы полученный json выглядел лучше, вы можете использовать эту функцию, которую я написал некоторое время go:

function Format-Json {
    <#
    .SYNOPSIS
        Prettifies JSON output.
    .DESCRIPTION
        Reformats a JSON string so the output looks better than what ConvertTo-Json outputs.
    .PARAMETER Json
        Required: [string] The JSON text to prettify.
    .PARAMETER Minify
        Optional: Returns the json string compressed.
    .PARAMETER Indentation
        Optional: The number of spaces (1..1024) to use for indentation. Defaults to 2.
    .PARAMETER AsArray
        Optional: If set, the output will be in the form of a string array, otherwise a single string is output.
    .EXAMPLE
        $json | ConvertTo-Json  | Format-Json -Indentation 4
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Json,

        [ValidateRange(1, 1024)]
        [int]$Indentation = 2,

        [switch]$AsArray
    )

    # If the input JSON text has been created with ConvertTo-Json -Compress
    # then we first need to reconvert it without compression
    if ($Json -notmatch '\r?\n') {
        $Json = ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100
    }

    $indent = 0
    $regexUnlessQuoted = '(?=([^"]*"[^"]*")*[^"]*$)'

    $result = $Json -split '\r?\n' |
        ForEach-Object {
            # If the line contains a ] or } character, 
            # we need to decrement the indentation level unless it is inside quotes.
            if ($_ -match "[}\]]$regexUnlessQuoted") {
                $indent = [Math]::Max($indent - $Indentation, 0)
            }

            # Replace all colon-space combinations by ": " unless it is inside quotes.
            $line = (' ' * $indent) + ($_.TrimStart() -replace ":\s+$regexUnlessQuoted", ': ')

            # If the line contains a [ or { character, 
            # we need to increment the indentation level unless it is inside quotes.
            if ($_ -match "[\{\[]$regexUnlessQuoted") {
                $indent += $Indentation
            }
            # ConvertTo-Json returns all single-quote characters as Unicode Apostrophs \u0027
            # see: https://stackoverflow.com/a/29312389/9898643
            $line # -replace '\\u0027', "'"
        }

    if ($AsArray) { return $result }
    return $result -Join [Environment]::NewLine
}

, а затем преобразовать измененный объект следующим образом:

$json | ConvertTo-Json -Depth 5 | Format-Json

Результат:

{
  "controlType": 3,
  "id": "a9ed7796-5545-4623-a943-5be42762691d",
  "position": {
    "zoneIndex": 1,
    "sectionIndex": 1,
    "controlIndex": 1,
    "layoutIndex": 1
  },
  "webPartId": "c70391ea-0b10-4ee9-b2b4-006d3fcad0cd",
  "webPartData": {
    "id": "c70391ea-0b10-4ee9-b2b4-006d3fcad0cd",
    "instanceId": "a9ed7796-5545-4623-a943-5be42762691d",
    "title": "Quick links",
    "description": "Add links to important documents and pages.",
    "serverProcessedContent": {
      "htmlStrings": {

      },
      "searchablePlainTexts": {
        "items[0].title": "Yahoo",
        "items[1].title": "Google",
        "items[2].title": "Stack Overflow"
      },
      "imageSources": {
        "items[0].rawPreviewImageUrl": "https://s.yimg.com/cv/apiv2/social/images/yahoo_default_logo.png"
      },
      "links": {
        "baseUrl": "https://bbpocoutlook.sharepoint.com/sites/tl23",
        "items[0].sourceItem.url": "https://yahoo.com",
        "items[1].sourceItem.url": "https://google.com",
        "items[2].sourceItem.url": "https://stackoverflow.com/"
      },
      "componentDependencies": {
        "layoutComponentId": "706e33c8-af37-4e7b-9d22-6e5694d92a6f"
      }
    },
    "dataVersion": "2.2",
    "properties": {
      "items": [
        {
          "sourceItem": "@{itemType=2; fileExtension=; progId=}",
          "thumbnailType": 3,
          "id": 2,
          "description": "",
          "altText": ""
        },
        {
          "sourceItem": "@{itemType=2; fileExtension=; progId=}",
          "thumbnailType": 3,
          "id": 1,
          "description": "",
          "altText": ""
        }
      ],
      "isMigrated": true,
      "layoutId": "List",
      "shouldShowThumbnail": true,
      "buttonLayoutOptions": {
        "showDescription": false,
        "buttonTreatment": 2,
        "iconPositionType": 2,
        "textAlignmentVertical": 2,
        "textAlignmentHorizontal": 2,
        "linesOfText": 2
      },
      "listLayoutOptions": {
        "showDescription": false,
        "showIcon": true
      },
      "waffleLayoutOptions": {
        "iconSize": 1,
        "onlyShowThumbnail": false
      },
      "hideWebPartWhenEmpty": true,
      "dataProviderId": "QuickLinks",
      "webId": "b5fdf80c-54ce-410f-a50d-910ea2e33250",
      "siteId": "0c8f4c9a-71e6-4fc0-8355-9b52f0a7eb3a"
    }
  },
  "emphasis": {

  },
  "reservedHeight": 132,
  "reservedWidth": 744,
  "addedFromPersistedData": true
}
...