locked
Powershell loop to check if DNS record exists RRS feed

  • Question

  • Hi,

    As part of a script I am developing, I'm looking to check external DNS for a txt value. I don't want the script to carry on until the value has been verified:

    So I have a variable $Domains which outputs the below and I need this to work for each domain in the variable:

    Label: mydomain.com
    Text: 12345678

    Label: mydomain.net
    Text: 87654321

    The command I want to use for validation is resolve-dnsname -name mydomain.com -Type txt.

    An example output is below:

    Name                                     Type   TTL   Section    Strings                                 
    ----                                         ----     ---   -------    -------                                  
    mydomain.com                         TXT    331   Answer     {12345678} 

    I'm sure its very simple what I need, I was thinking DO UNTIL but not sure how to do this with a loop aswell.

    Any advice greatly appreciated.


    Tuesday, May 30, 2017 11:26 AM

All replies

  • Hi there!

    Maybe something like this would help you get going?

    $domains = @('testdomain1.com', 'testdomain2.com')
    
    ForEach ($domain in $domains) {
        Do {
            $resolveDomain = (Resolve-DnsName -Name $domain -Type TXT | Where-Object { $_.Strings -ne '' } | Measure-Object).Count
    
            If ($resolveDomain -eq 0) {
                Write-Host "Didn't find any records. Sleeping for 5 seconds and trying again"
                Start-Sleep -Seconds 5
            }
            Else {
                Write-Host "Found a record for $domain, wohoo! Continuing on..."
            }
        }
        Until ($resolveDomain -gt 0)
    }

    Hope it helped you a little bit!

    Best Regards
    Andreas

    Tuesday, May 30, 2017 12:04 PM
  • To test a DNS TTX record for a value we would do this:

    if($rec = Resolve-Name -Name $name -ErrorAction 0){
        Write-Host "Domain $name found"
    if($rec.Text -eq $text){
    Write-Host "text value is correct"
    }else{
    Write-Host "text value does not match"
    } }else{ Write-Host "Domain $name not found" }

    Start by reading the help for the CmdLet:

    help Resolve-Name -full

    Take some time to first learn basic PowerShell as it will make all of this much easier.  Guessing will not help yuo build useful solutions.

    Stating that you have some arbitrary variable with something undefined in it is not of much help.  Is the variable a hash? Is it a list of  strings?  What is it?  How did you get it?

    PowerShell is an object system.  You must be explicit in your questions.


    \_(ツ)_/


    Tuesday, May 30, 2017 12:26 PM