Search code examples
apiazure-powershellazure-purview

Create Azure Purview collection using API and Powershell


This is the first time I am working with API.

I am trying to create a purview subcollection using API and powershell.

$tenantID = "XXXXXXXXXXXXXXXXXXXXXXX"

$url = "https://login.microsoftonline.com/$tenantID/oauth2/token"

$params = @{ client_id = "XXXXXXXXXXXXXXXXXXXXXXX"; client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXX"; grant_type = "client_credentials"; resource = ‘https://purview.azure.net’ }

$bearertoken = Invoke-WebRequest $url -Method Post -Body $params -UseBasicParsing | ConvertFrom-Json

$accesstoken = ConvertTo-SecureString $bearertoken.access_token -AsPlainText -Force

$purviewendpoint = "https://testpurview.purview.azure.com/account"

$url = "$purviewendpoint/collections/newcollection1?api-version=2019-11-01-preview"

$childcollection = @"
  {
    "parentCollection": {
      "referenceName": "**testpurview**"
    }
  }
"@

Invoke-RestMethod -Method PUT -Uri $url -Body $childcollection -Token $accesstoken

Steps I tried:

Created a bearer token. Created a variable for access_token from bearer token.

newcollection1: new subcollection which I want to create.

testpurview : This is the root collection of my Purview account.

Can someone help me if this is the correct way to create collection?


Solution

  • You may try the below approach.

    $tenantId = "<tenant-id>"
    $clientId = "<client-id>"
    $clientSecret = "<client-secret>"
    $accountName = "<purview-account-name>"
    $parentCollectionId = "<parent-collection-id>"
    $subcollectionName = "<subcollection-name>"
    
    $context = Connect-AzAccount -TenantId $tenantId -ServicePrincipal -Credential (New-Object System.Management.Automation.PSCredential($clientId, (ConvertTo-SecureString $clientSecret -AsPlainText -Force)))
    
    $token = $context.TokenCache.ReadItems() | Where-Object { $_.Resource -eq "https://purview.azure.net" } | Select-Object -First 1
    
    $body = @{
        name = $subcollectionName
    }
    
    # Send the request to create the subcollection
    $uri = "https://$accountName.purview.azure.com/collections/$parentCollectionId/subcollections?api-version=2021-07-01-preview"
    Invoke-RestMethod -Method Post -Uri $uri -Headers @{ Authorization = "Bearer $($token.AccessToken)" } -Body ($body | ConvertTo-Json)