Welcome › Forums › General PowerShell Q&A › Update multiple DNS records with CSV and foreach loop
- This topic has 2 replies, 2 voices, and was last updated 2 weeks ago by
Participant.
-
AuthorPosts
-
-
January 2, 2021 at 3:10 pm #283765
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):
PowerShell12345name,iptest1,10.10.105.240test2,10.10.105.241test3,10.10.105.242test4,10.10.105.243Working addition of records:
PowerShell12345678Import-Csv .\file.csv | foreach {Add-DnsServerResourceRecordA `-Name $_.name `-ZoneName example.com `-IPv4Address $_.ip}I can update individual records as:
PowerShell1234$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.comHowever, 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:
PowerShell12345name,iptest1,10.10.106.240test2,10.10.106.241test3,10.10.106.242test4,10.10.106.243Non working code that creates additional records with new IP:
PowerShell12345678Import-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
-
January 2, 2021 at 4:44 pm #283783
Well, it looks like the resolution was indeed simple. Removing the single quotes from the ‘parse’ argument allows the loop to succeed:
PowerShell12345678Import-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
-
January 4, 2021 at 8:45 am #283975
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
-
-
AuthorPosts
- You must be logged in to reply to this topic.