ahora con este scrip
# Connect to Azure and set the subscription context
Connect-AzAccount -Subscription Eng_Dublin

# Define the Azure Key Vault URL
$akvUrl = "https://acc-insights-canprd-kv.vault.azure.net/"

# Function to retrieve secrets from Azure Key Vault
Function Get-SecretFromAKV {
    param (
        [string]$secretName
    )
    try {
        $secret = Invoke-RestMethod -Uri "$akvUrl/secrets/$secretName/?api-version=7.0" -Method Get -Headers @{ "Authorization" = "Bearer $token" }
        return $secret.value
    } catch {
        Write-Error "Failed to retrieve secret {0}: {1}" -f $secretName, $_.Exception.Message
        return $null
    }
}

# Retrieve secrets needed for authentication
$SdevAKV = "mmAKVdev"
$tenantId = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-TenantId" -AsPlainText
$clientId = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-AppID" -AsPlainText
$clientSecret = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-AppSecret" -AsPlainText

# Acquire an Azure AD Access Token for Power BI
$authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
    grant_type    = "client_credentials"
    resource      = "https://analysis.windows.net/powerbi/api"
    client_id     = $clientId
    client_secret = $clientSecret
}

try {
    $response = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $body
    $accessToken = $response.access_token
    Write-Output "Successfully acquired Power BI access token."
} catch {
    Write-Error "Failed to acquire Power BI token: $_.Exception.Message"
    return
}

# Define API Base URL and Required IDs
$apiBaseUrl = "https://api.powerbi.com/v1.0/myorg/groups/"
$workspaceId = "c53bc7f1-ff5c-44ff-901f-3858089aaa17"
$caNonProdCapacityId = "0D8C5E3B-E86B-4182-B5E4-E4FE83C9BDED"
$p1CapacityId = "4F327CC4-4A3B-456B-BCCB-C0ED6E2B739C"
$userEmail = "ihand@accela.com"

# Function to handle API calls
function Invoke-Api {
    param (
        [string]$method,
        [string]$url,
        [hashtable]$body = $null
    )

    $headers = @{ "Authorization" = "Bearer $accessToken" }
    try {
        $bodyJson = if ($body -is [System.Collections.Hashtable]) {
            $body | ConvertTo-Json -Compress
        } else {
            $body
        }
        
        $response = Invoke-RestMethod -Method $method -Uri $url -Headers $headers -Body $bodyJson -ContentType "application/json"
        return $response
    } catch {
        Write-Error "API call to $url failed: $_.Exception.Message"
        return $null
    }
}

# Function to check if a user exists in the workspace
function CheckUserExists {
    param (
        [string]$url,
        [string]$email
    )

    try {
        $response = Invoke-Api -method "GET" -url $url
        $response.value | ForEach-Object { if ($_.emailAddress -eq $email) { return $true } }
        return $false
    } catch {
        Write-Error "Failed to check user existence: $_"
        return $false
    }
}

# Collect responses to store data
$responses = @()

# Step 1: Assign workspace to CA nonprod capacity
$assignCapacityUrl = "$apiBaseUrl$workspaceId/AssignToCapacity"
$assignToNonProd = Invoke-Api -method "POST" -url $assignCapacityUrl -body @{ capacityId = $caNonProdCapacityId }
$responses += [pscustomobject]@{ Step = "Assigned to CA nonprod capacity"; Status = $null -ne $assignToNonProd; Response = $assignToNonProd }

# Step 2: Assign workspace back to P1 capacity
$assignToP1 = Invoke-Api -method "POST" -url $assignCapacityUrl -body @{ capacityId = $p1CapacityId }
$responses += [pscustomobject]@{ Step = "Assigned to P1 capacity"; Status = $null -ne $assignToP1; Response = $assignToP1 }

# Step 3: Get workspace information
$workspaceInfoUrl = "$apiBaseUrl$workspaceId"
$workspaceInfo = Invoke-Api -method "GET" -url $workspaceInfoUrl
$responses += [pscustomobject]@{ Step = "Get WS information"; Status = $null -ne $workspaceInfo; Response = $workspaceInfo }

# Step 4: Get dataset information and last refresh status
$datasetsUrl = "$apiBaseUrl$workspaceId/datasets"
$datasetsInfo = Invoke-Api -method "GET" -url $datasetsUrl
$responses += [pscustomobject]@{ Step = "Get DS information"; Status = $null -ne $datasetsInfo; Response = $datasetsInfo }

foreach ($dataset in $datasetsInfo.value) {
    $datasetId = $dataset.id
    $datasetName = $dataset.name
    $refreshUrl = "$apiBaseUrl$workspaceId/datasets/$datasetId/refreshes?\$top=1"
    $refreshStatus = Invoke-Api -method "GET" -url $refreshUrl
    $responses += [pscustomobject]@{ Step = "Get last refresh status for $datasetName"; Status = $null -ne $refreshStatus; Response = $refreshStatus }
}

# Step 5: Add a user to the workspace as Viewer
$addUserUrl = "$apiBaseUrl$workspaceId/users"
$existCheck = CheckUserExists -url $addUserUrl -email $userEmail

if (-not $existCheck) {
    $addUserResponse = Invoke-Api -method "POST" -url $addUserUrl -body @{ emailAddress = $userEmail; groupUserAccessRight = "Viewer" }
    $responses += [pscustomobject]@{ Step = "Added user as Viewer"; Status = $null -ne $addUserResponse; Response = $addUserResponse }
}

# Step 6: Get gateway information
$gatewaysUrl = "https://api.powerbi.com/v1.0/myorg/gateways"
$gatewaysInfo = Invoke-Api -method "GET" -url $gatewaysUrl
$responses += [pscustomobject]@{ Step = "Get gateway information"; Status = $null -ne $gatewaysInfo; Response = $gatewaysInfo }

# Export comprehensive responses to CSV
try {
    $csvPath = [System.IO.Path]::Combine([System.Environment]::GetFolderPath('MyDocuments'), "responses.csv")

    $formattedResponses = $responses | ForEach-Object {
        [pscustomobject]@{
            Step         = $_.Step
            Status       = if ($_.Status) { "Success" } else { "Failed" }
            DetailedInfo = if ($_.Response) { ($_.Response | ConvertTo-Json -Compress) } else { "No response" }
        }
    }

    $formattedResponses | Export-Csv -Path $csvPath -NoTypeInformation
    Write-Output "Responses saved to $csvPath"
} catch {
    Write-Error "Failed to export responses to CSV: $_"
}