-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGet-OpenGraph.ps1
More file actions
75 lines (66 loc) · 2.48 KB
/
Get-OpenGraph.ps1
File metadata and controls
75 lines (66 loc) · 2.48 KB
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
function Get-OpenGraph
{
<#
.SYNOPSIS
Gets Open Graph metadata for a given URL.
.DESCRIPTION
Gets Open Graph metadata for a given URL.
[Open Graph](https://ogp.me/) is a protocol that enables any web page to become a rich object in a social graph.
It is used many social networks to display rich content when links are shared.
This function retrieves the Open Graph metadata from a given URL and returns it as a custom object.
.EXAMPLE
Get-OpenGraph -Url https://abc.com/
.EXAMPLE
'https://cnn.com/',
'https://msnbc.com/',
'https://fox.com/' |
Get-OpenGraph
#>
[Alias('openGraph','ogp')]
[CmdletBinding(PositionalBinding=$false)]
param(
# The URL that may contain Open Graph metadata
[Parameter(ValueFromPipelineByPropertyName)]
[Uri]
$Url,
# A dictionary of additional Open Graph metadata to include in the result
[Parameter(ValueFromPipelineByPropertyName)]
[Collections.IDictionary]
$Data,
# If set, forces the function to retrieve the Open Graph metadata even if it is already cached.
[Parameter(ValueFromPipelineByPropertyName)]
[switch]
$Force
)
begin {
# Make a regex to match meta tags
$metaRegex = [Regex]::new('<meta.+?/>','IgnoreCase','00:00:00.1')
if (-not $script:OpenGraphCache) {
$script:OpenGraphCache = [Ordered]@{}
}
}
process {
# Declare an empty object to hold the Open Graph metadata
$openGraphMetadata = [Ordered]@{PSTypeName='OpenGraph'}
if ($Url) {
if ($script:OpenGraphCache[$url] -and -not $Force) {
return $script:OpenGraphCache[$url]
}
$restResponse = Invoke-RestMethod -Uri $Url
foreach ($match in $metaRegex.Matches("$restResponse")) {
$matchXml = "$match" -as [xml]
if ($matchXml.meta.property -and $matchXml.meta.content) {
$openGraphMetadata[$matchXml.meta.property] = $matchXml.meta.content
}
}
$script:OpenGraphCache[$url] = $openGraphMetadata
}
if ($Data) {
foreach ($key in $Data.Keys) {
$openGraphMetadata[$key] = $Data[$key]
}
}
if (-not $openGraphMetadata.Count) { return }
[PSCustomObject]$openGraphMetadata
}
}