UtmLink.psm1
|
function New-UtmLink { <# .SYNOPSIS Build a campaign URL with UTM parameters: lowercase values, spaces turned into hyphens, existing query kept. .EXAMPLE New-UtmLink -Url https://example.com/pricing -Source linkedin -Medium paid-social -Campaign 'Q1 Launch' #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Url, [Parameter(Mandatory)][string]$Source, [Parameter(Mandatory)][string]$Medium, [Parameter(Mandatory)][string]$Campaign, [string]$Term, [string]$Content ) function Norm([string]$v) { [uri]::EscapeDataString(($v.Trim().ToLowerInvariant() -replace '\s+', '-')) } $u = [uri]$Url if (-not $u.IsAbsoluteUri -or $u.Scheme -notin 'http', 'https') { throw "Url must be an absolute http(s) address: $Url" } $keep = @() if ($u.Query.Length -gt 1) { $keep = $u.Query.Substring(1) -split '&' | Where-Object { $_ -and $_ -notmatch '^utm_' } } $utm = [ordered]@{ utm_source = $Source; utm_medium = $Medium; utm_campaign = $Campaign } if ($Term) { $utm['utm_term'] = $Term } if ($Content) { $utm['utm_content'] = $Content } $pairs = @($keep) + @($utm.GetEnumerator() | ForEach-Object { "$($_.Key)=$(Norm $_.Value)" }) $base = $Url -replace '[?#].*$', '' $frag = if ($u.Fragment) { $u.Fragment } else { '' } "$base`?$($pairs -join '&')$frag" } function Test-UtmLink { <# .SYNOPSIS Check a URL for UTM mistakes: missing source, medium or campaign, upper case, spaces, duplicates. .EXAMPLE Test-UtmLink -Url 'https://example.com/?utm_source=LinkedIn&utm_medium=paid social' #> [CmdletBinding()] param([Parameter(Mandatory, ValueFromPipeline)][string]$Url) process { $problems = New-Object System.Collections.Generic.List[string] $q = if ($Url -match '\?([^#]*)') { $Matches[1] } else { '' } $p = @{} foreach ($pair in ($q -split '&' | Where-Object { $_ })) { $kv = $pair -split '=', 2; $k = $kv[0]; $v = if ($kv.Count -gt 1) { [uri]::UnescapeDataString($kv[1]) } else { '' } if ($k -like 'utm_*') { if ($p.ContainsKey($k)) { $problems.Add("duplicate $k") } $p[$k] = $v if ($v -cmatch '[A-Z]') { $problems.Add("$k has upper case: '$v'") } if ($v -match '\s') { $problems.Add("$k has a space: '$v'") } if ($v -eq '') { $problems.Add("$k is empty") } } } foreach ($need in 'utm_source', 'utm_medium', 'utm_campaign') { if (-not $p.ContainsKey($need)) { $problems.Add("missing $need") } } [pscustomobject]@{ Url = $Url; Ok = ($problems.Count -eq 0); Problems = $problems.ToArray() } } } Export-ModuleMember -Function New-UtmLink, Test-UtmLink |