1+ function Get-OpenGraph
2+ {
3+ <#
4+ . SYNOPSIS
5+ Gets Open Graph metadata for a given URL.
6+ . DESCRIPTION
7+ Gets Open Graph metadata for a given URL.
8+
9+ [Open Graph](https://ogp.me/) is a protocol that enables any web page to become a rich object in a social graph.
10+
11+ It is used many social networks to display rich content when links are shared.
12+
13+ This function retrieves the Open Graph metadata from a given URL and returns it as a custom object.
14+ . EXAMPLE
15+ Get-OpenGraph -Url https://abc.com/
16+ . EXAMPLE
17+ 'https://cnn.com/',
18+ 'https://msnbc.com/',
19+ 'https://fox.com/' |
20+ Get-OpenGraph
21+ #>
22+ [Alias (' openGraph' , ' ogp' )]
23+ param (
24+ # The URL that may contain Open Graph metadata
25+ [Parameter (ValueFromPipeline , ValueFromPipelineByPropertyName )]
26+ [Uri ]
27+ $Url ,
28+
29+ # A dictionary of additional Open Graph metadata to include in the result
30+ [Parameter (ValueFromPipelineByPropertyName )]
31+ [Collections.IDictionary ]
32+ $Data
33+ )
34+
35+ begin {
36+ # Make a regex to match meta tags
37+ $metaRegex = [Regex ]::new(' <meta.+?/>' , ' IgnoreCase' , ' 00:00:00.1' )
38+ }
39+
40+ process {
41+ # Declare an empty object to hold the Open Graph metadata
42+ $openGraphMetadata = [Ordered ]@ {PSTypeName = ' OpenGraph' }
43+ if ($Url ) {
44+ $restResponse = Invoke-RestMethod - Uri $Url
45+ foreach ($match in $metaRegex.Matches (" $restResponse " )) {
46+ $matchXml = " $match " -as [xml ]
47+ if ($matchXml.meta.property -and $matchXml.meta.content ) {
48+ $openGraphMetadata [$matchXml.meta.property ] = $matchXml.meta.content
49+ }
50+ }
51+ }
52+ if ($Data ) {
53+ foreach ($key in $Data.Keys ) {
54+ $openGraphMetadata [$key ] = $Data [$key ]
55+ }
56+ }
57+
58+ if (-not $openGraphMetadata.Count ) { return }
59+
60+ [PSCustomObject ]$openGraphMetadata
61+ }
62+ }
0 commit comments