RoG
RoG

Reputation: 421

Powershell script doesn't use the updated IP address in the hosts file when Invoke Invoke-RestMethod

I have a Powershell script that runs on an array of IP addresses, for each one, it adds the entry to the hosts file:

add-host $hostsFilePath $ipAddress $domainName

using these methods: add-host and remove-host methods

then I run:

Invoke-RestMethod -Uri $subsequentEndpoint -Method Post -Headers $headers -Body $body

in the end of the iteration I remove the line I added.

the request $subsequentEndpoint start with the domain name but it doesn't get to the IP address I just updated in the host file. It uses an old value of IP address I added in the first iteration of the loop.

How can I resolve it? maybe it's DNS cache issue?

# Define an array of IP addresses
$ipAddresses = @(
   
    "1.2.3.4", 
    "5.6.7.8", 
    "5.6.3.3"

)

foreach ($ipAddress in $ipAddresses) {
    add-host $hostsFilePath  $ipAddress $domainName
    
    $headers = @{
        "Authorization" = "Bearer ******"
        "content-type" = "application/json; charset=utf-8"
    }

    $requestCount = 10
    
    # flushed the DNS Resolver Cache. So the requests will use the new entry in the hosts file
    #[System.Net.ServicePointManager]::DnsRefreshTimeout = 0

    for ($i = 1; $i -le $requestCount; $i++) {
        $subsequentResponse = Invoke-RestMethod -Uri $subsequentEndpoint -Method Post -Headers $headers -Body $body
    }

    remove-host $hostsFilePath  $ipAddress $domainName
}

Upvotes: 1

Views: 259

Answers (0)

Related Questions