Public/TenantConfiguration/Baseline/Add-SecurityBaselines.ps1

function Add-SecurityBaselines {
    param(
      [Parameter(Mandatory)]
      [string]$TenantId
    )
  
    try {
      Connect-CustomerGraph -CustomerTenantId $TenantId
  
      $SecurityBaselines = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/deviceManagement/intents").value
  
      $SecurityBaselineFiles = Get-ChildItem -Path "$PSScriptRoot\SecurityBaselines" -Filter *.json
      foreach ($SecurityBaselineFile in $SecurityBaselineFiles) {
        $SecurityBaseline = Get-Content -Path $SecurityBaselineFile.FullName | ConvertFrom-Json -AsHashtable -Depth 100
  
        if ($SecurityBaselines.displayName -contains $SecurityBaseline.displayName) {
          Write-Host "Security baseline profile '$($SecurityBaseline.displayName)' already exists, not creating.." -ForegroundColor Yellow
        }
        else {
          $SecurityBaseline = Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/beta/deviceManagement/templates/034ccd46-190c-4afc-adf1-ad7cc11262eb/createInstance" -Body $SecurityBaseline
          
          Write-Host "Created Security baseline profile '$($SecurityBaseline.DisplayName)'!" -ForegroundColor Green
  
          Invoke-MgGraphRequest -METHOD POST -Uri "https://graph.microsoft.com/beta/deviceManagement/intents/$($SecurityBaseline.id)/assign" -Body @{
            "assignments" = @(
              @{"target" = @{
                "@odata.type" = "#microsoft.graph.allDevicesAssignmentTarget" }
              }) 
            } | Out-Null
          
            Write-Host "Assigned Security baseline profile '$($SecurityBaseline.displayName)' to all devices." -ForegroundColor Green
            
        }
      }
    }
    catch {
      throw "Failed to add Security baseline configuration: $_"
    }
  }