Home > database >  How to modify data in a format-table result?
How to modify data in a format-table result?

Time:12-21

Trying to make a powershell script that tracks link clicks.

I have three goals:

  1. change destination to name
  2. Filter out destinations that are not a file type
  3. Only display name of file, not the URL or extension
# Set the API key and endpoint
$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"

# Make the API call and store the response
$response = Invoke-RestMethod -Method GET -Uri $endpoint -Headers @{ "apikey" = $apiKey } | Format-Table -Property clicks, destination
$response

clicks destination
------ -----------
    11 https://github.com/file1.ps1
     4 https://github.com/file2.ps1
     2 https://github.com/main.zip
     1 https://www.instagram.com

Desired Result

clicks destination
------ -----------
    11 file1
     4 file2
     2 main

CodePudding user response:

Format-Table doesn't perform collection filtering hence is not the right cmdlet for this use case. Also, for 2 property objects, it is not needed at all since default formatting output will be a table by default for objects with 4 properties or less.

Invoke-RestMethod -Method GET -Uri $endpoint -Headers @{ "apikey" = $apiKey } | ForEach-Object {
    $lastSegment = ($_.destination -as [uri]).Segments | Select-Object -Last 1
    if([System.IO.Path]::GetExtension($lastSegment)) {
        [pscustomobject]@{
            Clicks = $_.Clicks
            Name   = [System.IO.Path]::GetFileNameWithoutExtension($lastSegment)
        }
    }
}

CodePudding user response:

This is a modification of Santiagos answer. I couldn't quite get his to work. I'm sure this can be optimized however.

$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"

$r = Invoke-RestMethod -Method GET -Uri $endpoint -Headers @{ "apikey" = $apiKey } 
    ForEach($l in $r){$s = ($l.destination -as [uri]).Segments[-1]
        if([System.IO.Path]::GetExtension($s)) {
            [pscustomobject]@{
            Clicks = $l.Clicks
            Name   = [System.IO.Path]::GetFileNameWithoutExtension($s)
        }
    }
}
  • Related