# Exporting to CSV

**URL:** <https://community.dynatrace.com/t/exporting-to-csv/45644>\
**Category:** Dynatrace API\
**Tags:** dynatrace-api\
**Created:** [May 17, 2024, 8:20am UTC](https://community.dynatrace.com/t/exporting-to-csv/45644 "2024-05-17T08:20:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![geonaute123](https://avatars.discourse-cdn.com/v4/letter/g/e99b99/32.png) [@geonaute123](https://community.dynatrace.com/u/geonaute123)\
**Post date:** [May 17, 2024, 8:20am UTC](https://community.dynatrace.com/t/exporting-to-csv/45644/1 "2024-05-17T08:20:06Z")

</div>

I am trying to export 2 metrics of a specific management zone to CSV: the number of transactions and response time, however I get the following error with this powershell code:

[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

$DYNATRACE\_API\_TOKEN = ‘tu\_token\_de\_acceso’  
$ZONA\_GESTION = ‘Mngz-WSZonaClienteSFC’

$METRICA\_TRANSACCIONES = “builtin:service.requestCount.total:filter(eq(mzName,‘$ZONA\_GESTION’)):splitBy()”  
$METRICA\_TIEMPO\_RESPUESTA = “builtin:service.response.time:filter(eq(mzName,‘$ZONA\_GESTION’)):splitBy()”

$respuesta\_transacciones = Invoke-RestMethod -Uri “https://{tu-dynatrace-managed}/e/{tu-environment-id}/api/v2/metrics/query?metricSelector=$METRICA\_TRANSACCIONES” -Headers @{ “Authorization” = “Api-Token $DYNATRACE\_API\_TOKEN”; “Content-Type” = “application/json” } -Method Get  
$respuesta\_tiempo\_respuesta = Invoke-RestMethod -Uri “https://{tu-dynatrace-managed}/e/{tu-environment-id}/api/v2/metrics/query?metricSelector=$METRICA\_TIEMPO\_RESPUESTA” -Headers @{ “Authorization” = “Api-Token $DYNATRACE\_API\_TOKEN”; “Content-Type” = “application/json” } -Method Get

if ($respuesta\_transacciones -eq $null -or $respuesta\_tiempo\_respuesta -eq $null) {  
Write-Output “Error al obtener los datos.”  
exit  
}

$transacciones = $respuesta\_transacciones.result[0].data | ForEach-Object { [PSCustomObject]@{ ServiceID = $\_.dimensions[0]; Transactions = $\_.values[0] } }  
$tiempo\_respuesta = $respuesta\_tiempo\_respuesta.result[0].data | ForEach-Object { [PSCustomObject]@{ ServiceID = $\_.dimensions[0]; ResponseTime = $\_.values[0] } }

$datos\_combinados = $transacciones | ForEach-Object {  
$id = $\_.ServiceID  
$respuesta = $tiempo\_respuesta | Where-Object { $\_.ServiceID -eq $id }  
[PSCustomObject]@{ ServiceID = $\_.ServiceID; Transactions = $\_.Transactions; ResponseTime = $respuesta.ResponseTime }  
}

$datos\_combinados | Export-Csv -Path “dynatrace\_service\_metrics.csv” -NoTypeInformation  
Write-Output “Datos exportados exitosamente a dynatrace\_service\_metrics.csv”

The error is: line 6 character 28 and line 7 char 31: Invalid operation (system.net.nhttpwebrequest:httpwebrequest)

fullyqualifiederrorid: webcmdletwebresponseexception,microsoft.powershell.commands.invokerestmethodcommand

What I am doing wrong? Thanks.

---

<div class="post-metadata">

**Author:** ![MaximilianoML](https://dub1.discourse-cdn.com/dynatrace/user_avatar/community.dynatrace.com/maximilianoml/32/25038_2.png) [@MaximilianoML](https://community.dynatrace.com/u/MaximilianoML)\
**Post date:** [May 17, 2024, 8:56am UTC](https://community.dynatrace.com/t/exporting-to-csv/45644/2 "2024-05-17T08:56:03Z")

</div>

Hello,&nbsp;[@geonaute123](https://community.dynatrace.com/user/75324)!

First of all, I’m not a PowerShell Script Guru, but I’ll try to help you.

I did some changes in your code and I’ll let my code snippet and my explanation below. 🙂

```php
# Disable SSL certificate validation (use with caution)
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

# Define variables
$DYNATRACE_API_TOKEN = 'your_access_token'
$ZONA_GESTION = 'Mngz-WSZonaClienteSFC'
$DYNATRACE_MANAGED = 'your_dynatrace_managed'
$ENVIRONMENT_ID = 'your_environment_id'

# Define metric selectors
$METRICA_TRANSACCIONES = "builtin:service.requestCount.total:filter(eq(mzName,'$ZONA_GESTION')):splitBy()"
$METRICA_TIEMPO_RESPUESTA = "builtin:service.response.time:filter(eq(mzName,'$ZONA_GESTION')):splitBy()"

# Perform API requests with error handling
try {
    $respuesta_transacciones = Invoke-RestMethod -Uri "https://$DYNATRACE_MANAGED/e/$ENVIRONMENT_ID/api/v2/metrics/query?metricSelector=$($METRICA_TRANSACCIONES)" -Headers @{ "Authorization" = "Api-Token $DYNATRACE_API_TOKEN"; "Content-Type" = "application/json" } -Method Get
    $respuesta_tiempo_respuesta = Invoke-RestMethod -Uri "https://$DYNATRACE_MANAGED/e/$ENVIRONMENT_ID/api/v2/metrics/query?metricSelector=$($METRICA_TIEMPO_RESPUESTA)" -Headers @{ "Authorization" = "Api-Token $DYNATRACE_API_TOKEN"; "Content-Type" = "application/json" } -Method Get
} catch {
    Write-Output "Error making the request: $_"
    exit
}

# Verify responses are not null
if ($respuesta_transacciones -eq $null -or $respuesta_tiempo_respuesta -eq $null) {
    Write-Output "Error obtaining data."
    exit
}

# Verify the response structure
if (-not $respuesta_transacciones.result -or -not $respuesta_tiempo_respuesta.result) {
    Write-Output "Unexpected response structure."
    exit
}

# Process the transaction data
$transacciones = $respuesta_transacciones.result[0].data | ForEach-Object { 
    [PSCustomObject]@{ 
        ServiceID = $_.dimensions[0]; 
        Transactions = $_.values[0] 
    } 
}

# Process the response time data
$tiempo_respuesta = $respuesta_tiempo_respuesta.result[0].data | ForEach-Object { 
    [PSCustomObject]@{ 
        ServiceID = $_.dimensions[0]; 
        ResponseTime = $_.values[0] 
    } 
}

# Combine the data based on ServiceID
$datos_combinados = $transacciones | ForEach-Object {
    $id = $_.ServiceID
    $respuesta = $tiempo_respuesta | Where-Object { $_.ServiceID -eq $id }
    [PSCustomObject]@{ 
        ServiceID = $_.ServiceID; 
        Transactions = $_.Transactions; 
        ResponseTime = $respuesta.ResponseTime 
    }
}

# Export combined data to CSV
$datos_combinados | Export-Csv -Path "dynatrace_service_metrics.csv" -NoTypeInformation
Write-Output "Data successfully exported to dynatrace_service_metrics.csv"

```

**Variable Definitions** :

- Ensure that the $DYNATRACE\_MANAGED and $ENVIRONMENT\_ID variables are correctly defined.
- Properly interpolate variables within the URL by using $($variable) syntax.

**Error Handling** :

- Added try-catch blocks around the API requests to catch and display any errors that occur during the HTTP requests.

**Response Verification** :

- Added checks to verify that the responses are not null and have the expected structure before processing the data.

**Processing and Combining Data** :

- Used ForEach-Object to process the transaction and response time data.
- Combined the data based on the ServiceID to ensure that the final CSV contains both metrics for each service.

---

<div class="post-metadata">

**Author:** ![geonaute123](https://avatars.discourse-cdn.com/v4/letter/g/e99b99/32.png) [@geonaute123](https://community.dynatrace.com/u/geonaute123)\
**Post date:** [May 17, 2024, 10:26am UTC](https://community.dynatrace.com/t/exporting-to-csv/45644/3 "2024-05-17T10:26:47Z")

</div>

Thanks for the answer. I am trying to get these 2 metrics to a CSV from a list of host that pertains to the “Mngz-WSZonaClienteSFC” management zone.
