-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShorten.ps1
79 lines (62 loc) · 2.17 KB
/
Shorten.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Path to your secrets file
$secretsPath = "$PSScriptRoot\secrets.psd1"
# Import the secrets file
$secrets = Import-PowerShellDataFile -Path $secretsPath
# Retrieve the Bitly API token from the secrets file
$bitlyToken = $secrets.BitlyToken
# Function to prompt for GitHub raw URL and validate it
function Get-GitHubRawUrl {
param (
[string]$PromptMessage = "Enter the GitHub raw URL (format: https://raw.githubusercontent.com/...): "
)
while ($true) {
$url = Read-Host -Prompt $PromptMessage
if ($url -match '^https://raw.githubusercontent.com') {
return $url
} else {
Write-Host "Invalid URL format. Please enter a valid GitHub raw URL." -ForegroundColor Red
}
}
}
# Function to build example text
function Build-ExampleText {
param (
[string]$longUrl,
[string]$shortUrl
)
$shortUrlNoProtocol = $shortUrl -replace '^https://', ''
return @"
# call using:
# powershell -Command "iex (irm $longUrl)"
# powershell -Command "iex (irm $shortUrl)"
# powershell -Command "iex (irm $shortUrlNoProtocol)"
# or if you are in powershell already call (URL is case sensitive)
# iex (irm $shortUrlNoProtocol)
"@
}
# Prompt the user to enter the GitHub raw URL
$longUrl = Get-GitHubRawUrl
# The Bitly API endpoint for shortening URLs
$bitlyApiUrl = "https://api-ssl.bitly.com/v4/shorten"
# Prepare the request headers
$headers = @{
"Authorization" = "Bearer $bitlyToken"
"Content-Type" = "application/json"
}
# Prepare the request body
$body = @{
"long_url" = $longUrl
} | ConvertTo-Json
# Make the request to the Bitly API
$response = Invoke-RestMethod -Uri $bitlyApiUrl -Method POST -Headers $headers -Body $body
# Output the shortened URL
$shortUrl = $response.link
Write-Host "Shortened URL: $shortUrl"
# Build and output the example text
$exampleText = Build-ExampleText -longUrl $longUrl -shortUrl $shortUrl
Write-Host $exampleText
# Write the example to Readme.md in the script root
$readmePath = "$PSScriptRoot\Readme-Install.md"
$exampleText | Out-File -FilePath $readmePath -Encoding utf8
# Inform the user
Write-Host "Example output written to Readme.md in the script root."