Last active
June 11, 2024 07:30
-
-
Save davidlu1001/1387c33c89fdd0e2f7ae60bb9ae85cb9 to your computer and use it in GitHub Desktop.
CheckAndAddCnames.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[Parameter(Mandatory = $false)] | |
[string[]]$CnameList, | |
[Parameter(Mandatory = $false)] | |
[string]$CnameListFilePath, | |
[Parameter(Mandatory = $true)] | |
[string]$TargetHostname, | |
[Parameter(Mandatory = $true)] | |
[string]$DnsServer, | |
[Parameter(Mandatory = $true)] | |
[string]$LookupZone | |
) | |
function CheckAndAddCname($cname, $target, $dnsServer, $zone) { | |
try { | |
$dnsRecord = Resolve-DnsName -Name $cname -Type CNAME -Server $dnsServer -ErrorAction SilentlyContinue | |
if ($dnsRecord -and $dnsRecord.QueryType -eq 'CNAME') { | |
Write-Host "CNAME $cname already exists, pointing to $($dnsRecord.NameHost). Skipping..." | |
} else { | |
Write-Host "Creating CNAME $cname pointing to $target..." | |
Add-DnsServerResourceRecordCName -HostNameAlias $target -Name $cname -ZoneName $zone -ComputerName $dnsServer | |
Write-Host "CNAME $cname created successfully." | |
} | |
} catch { | |
Write-Error "Error processing CNAME $cname : $_" | |
} | |
} | |
# Determine how to read CNAME list based on parameters provided | |
if (-not [string]::IsNullOrEmpty($CnameListFilePath)) { | |
if (Test-Path -Path $CnameListFilePath) { | |
$CnameList = Get-Content -Path $CnameListFilePath | |
} else { | |
Write-Error "The specified file at $CnameListFilePath does not exist." | |
return | |
} | |
} | |
if ($CnameList -eq $null -or $CnameList.Count -eq 0) { | |
Write-Error "No CNAMEs provided to process." | |
return | |
} | |
foreach ($cname in $CnameList) { | |
if (![string]::IsNullOrWhiteSpace($cname)) { | |
CheckAndAddCname -cname $cname -target $TargetHostname -dnsServer $DnsServer -zone $LookupZone | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment