Update multiple DNS records with CSV and foreach loop

Hi,

I am trying to update multiple DNS records using a CSV file and a foreach loop. Adding multiple records with CSV and foreach loop works fine.

CSV file (file.csv):

name,ip
test1,10.10.105.240
test2,10.10.105.241
test3,10.10.105.242
test4,10.10.105.243

Working addition of records:

Import-Csv .\file.csv | foreach {

	Add-DnsServerResourceRecordA `
	-Name $_.name `
	-ZoneName example.com `
	-IPv4Address $_.ip

	}

I can update individual records as:

$old = Get-DnsServerResourceRecord -ZoneName example.com -Name test1
$new = $old.Clone()
$new.RecordData.IPv4Address = [System.Net.IPAddress]::parse('10.10.106.35')
Set-DnsServerResourceRecord -NewInputObject $new -OldInputObject $old -ZoneName example.com

However, trying to incorporate the update into a CSV and foreach loop ends up adding additional records (2 records for test1, test2, etc., one record with original IP and one record with new IP):

CSV file:

name,ip
test1,10.10.106.240
test2,10.10.106.241
test3,10.10.106.242
test4,10.10.106.243

Non working code that creates additional records with new IP:

Import-Csv .\file.csv | foreach {

	$old = Get-DnsServerResourceRecord -ZoneName example.com -Name $_.name
	$new = $old.Clone()
	$new.RecordData.IPv4Address = [System.Net.IPAddress]::parse('$_.ip')
	Set-DnsServerResourceRecord -NewInputObject $new -OldInputObject $old -ZoneName example.com

	}

Can anyone shed some light on my mistake here?

Thanks,

HB

Well, it looks like the resolution was indeed simple. Removing the single quotes from the 'parse' argument allows the loop to succeed:
Import-Csv .\file.csv | foreach {

$old = Get-DnsServerResourceRecord -ZoneName example.com -Name $.name
$new = $old.Clone()
$new.RecordData.IPv4Address = [System.Net.IPAddress]::parse($
.ip)
Set-DnsServerResourceRecord -NewInputObject $new -OldInputObject $old -ZoneName example.com

}


I’m open to any suggestions if there is a better way to do this…

Thanks,

HB

Just to add some education to this. Single quotes are verbatim strings (no interpolation), so in the ‘$_.ip’ is literally that string not the ip property of the current item in the foreach-object loop. Recommend reviewing Get-Help about_quoting_rules