Skip to content

Instantly share code, notes, and snippets.

@unfo
Created October 25, 2025 09:47
Show Gist options
  • Select an option

  • Save unfo/6e86e4742a46fbece8cf172edc8739c5 to your computer and use it in GitHub Desktop.

Select an option

Save unfo/6e86e4742a46fbece8cf172edc8739c5 to your computer and use it in GitHub Desktop.

Revisions

  1. unfo created this gist Oct 25, 2025.
    60 changes: 60 additions & 0 deletions monitor-clipboard-clean.ps1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    # monitor-clipboard-clean.ps1
    # Cleans query params from leading youtu.be or instagram post URLs in the clipboard.
    # Example:
    # "https://youtu.be/0csxphA17bY?si=abc this is awesome"
    # -> "https://youtu.be/0csxphA17bY this is awesome"

    $ErrorActionPreference = 'SilentlyContinue'
    $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

    # Idle poll interval
    $intervalMs = 300

    # Regexes:
    # - YouTube short URLs (youtu.be/<id>[?query][#fragment])
    $reYouTube = '^(?<pre>\s*)(?<url>https://youtu\.be/[^?\s#]+)(?<query>\?[^\s#]*)?(?<frag>#[^\s]*)?(?<post>\s.*)?$'
    # - Instagram post URLs (https://(www.)?instagram.com/p/<id>/[?query][#fragment])
    $reInsta = '^(?<pre>\s*)(?<url>https://(?:www\.)?instagram\.com/p/[^/\s?#]+/)(?<query>\?[^\s#]*)?(?<frag>#[^\s]*)?(?<post>\s.*)?$'

    function Get-ClipboardSafe {
    try { return (Get-Clipboard -Raw) } catch { return $null }
    }

    function Clean-LeadingUrlIfTarget([string]$text) {
    if ([string]::IsNullOrEmpty($text)) { return $null }

    foreach ($re in @($reYouTube, $reInsta)) {
    $m = [regex]::Match($text, $re)
    if ($m.Success) {
    $pre = $m.Groups['pre'].Value
    $url = $m.Groups['url'].Value # base URL without query
    $frag = $m.Groups['frag'].Value # keep fragment if present
    $post = $m.Groups['post'].Value # everything after the URL (starting with a space if any)

    # Reconstruct WITHOUT the query string, preserving fragment & trailing text
    $clean = "$pre$url$frag$post"
    if ($clean -ne $text) { return $clean }
    return $null
    }
    }
    return $null
    }

    $last = $null
    while ($true) {
    Start-Sleep -Milliseconds $intervalMs

    $cur = Get-ClipboardSafe
    if ($null -eq $cur) { continue }

    if ($cur -ne $last) {
    $updated = Clean-LeadingUrlIfTarget $cur
    if ($updated) {
    Set-Clipboard -Value $updated
    Write-Host "[cleaned] $(Get-Date -Format HH:mm:ss) -> $updated"
    $last = $updated
    } else {
    $last = $cur
    }
    }
    }