-
Notifications
You must be signed in to change notification settings - Fork 29
/
Format-EscapedUrl.ps1
55 lines (45 loc) · 1.53 KB
/
Format-EscapedUrl.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<#
.SYNOPSIS
Escape URLs more aggressively.
.DESCRIPTION
Some characters such as apostrophes and parentheses are legal for URLs,
but are a hassle within certain formats (Markdown, JSON, SQL, &c).
This script URL-escapes these characters to %xx format.
.FUNCTIONALITY
Data formats
.INPUTS
System.Uri to escape.
.OUTPUTS
System.String containing the URL escaped for maximum compatibility.
.EXAMPLE
Format-EscapedUrl.ps1 -Clipboard
Updates the URL on the clipboard with a more aggressively escaped version.
.EXAMPLE
Format-EscapedUrl.ps1 "https://example.com/search(en-US)?q=Name%20%3D%20'System'&sort=y"
https://example.com/search%28en-US%29?q=Name%20%3D%20%27System%27&sort=y
#>
#Requires -Version 3
[CmdletBinding()][OutputType([string])] Param(
# The URL to format for maximum compatibility.
[Parameter(ParameterSetName='Uri',Position=0,ValueFromPipeline=$true,ValueFromRemainingArguments=$true,Mandatory=$true)]
[Alias('Url')][uri[]]$Uri,
# Indicates that the URL comes from the clipboard, and is updated on the clipboard.
[Parameter(ParameterSetName='Clipboard')][switch]$Clipboard
)
Begin
{
[char[]]$chars = ' ',"'",'(',')','[',']','$'
}
Process
{
if($Clipboard) {Get-Clipboard |Format-EscapedUrl.ps1 |Set-Clipboard}
else
{
foreach($u in $Uri)
{
$escaped = if($u.IsAbsoluteUri){$u.AbsoluteUri}else{$u.OriginalString}
foreach($c in $chars) {$escaped = $escaped.Replace([string]$c,('%{0:X2}' -f [int]$c))}
$escaped
}
}
}