PowerShell Invoke-RestMethod / CloudFlare API v4 Code Sample

If you're looking to create your own CloudFlare API v4-based PowerShell module, and would like some syntax examples, here's a simplified breakdown of my CloudFlareDynDns module on github, which I discuss in "Use PowerShell and CloudFlare API v4 to Dynamically Update CloudFlare DNS to your External IP".

 1# Set auth and subdomain information
 2$token = "1234567893feefc5f0q5000bfo0c38d90bbeb"
 3$email = "[email protected]"
 4$domain = "example.com"
 5$record = "homelab"
 6
 7# Get external IP
 8$ipaddr = Invoke-RestMethod https://ipinfo.io/json | Select-Object -ExpandProperty ip
 9
10$baseurl = "https://api.cloudflare.com/client/v4/zones"
11$zoneurl = "$baseurl/?name=$domain"
12
13# To login use...
14$headers = @{
15	'X-Auth-Key' = $token
16	'X-Auth-Email' = $email
17}
18
19# Get Zone info
20$zone = Invoke-RestMethod -Uri $zoneurl -Method Get -Headers $headers
21$zoneid = $zone.result[0].id
22
23$recordurl = "$baseurl/$zoneid/dns_records/?name=$record.$domain"
24
25# Get current DNS record
26$dnsrecord = Invoke-RestMethod -Uri $recordurl -Method Get -Headers $headers
27
28# If it exists, update, if not, add
29if ($dnsrecord.result -and $dnsrecord.result.Count -gt 0) {
30
31	$existing = $dnsrecord.result[0]
32	$recordid = $existing.id
33	$existing | Add-Member "content" $ipaddr -Force
34	$body = $existing | ConvertTo-Json
35
36	$updateurl = "$baseurl/$zoneid/dns_records/$recordid/"
37	$result = Invoke-RestMethod -Uri $updateurl -Method Put -Headers $headers -Body $body -ContentType "application/json"
38
39	Write-Output "Record $record.$domain has been updated to the IP $($result.result.content)"
40
41} else {
42	$newrecord = @{
43		"type" = "A"
44		"name" =  "$record.$domain"
45		"content" = $ipaddr
46	}
47
48	$body = $newrecord | ConvertTo-Json
49	$newrecordurl = "$baseurl/$zoneid/dns_records"
50	$request = Invoke-RestMethod -Uri $newrecordurl -Method Post -Headers $headers -Body $body -ContentType "application/json"
51	Write-Output "New record $record.$domain has been created with the ID $($request.result.id)"
52}

Note: In recent years, Cloudflare recommends using API Tokens with the Authorization header instead of legacy X-Auth-Key/X-Auth-Email. If you use an API Token, your headers would look like:

1$headers = @{ 'Authorization' = "Bearer $token" }