Reputation: 641
I have a powershell script that processes a bunch of DNS A records and I'm trying to filter out the default records (i.e. "@", "ForestDNSZones", etc). Just trying this with a simple if statement doesn't seem to work.
Code sample:
$zoneARecords = Get-DnsServerResourceRecord -ComputerName $DNSserver -ZoneName $zoneName | ?{$_.RecordType -eq "A"}
foreach ($record in $zoneARecords) {
$hostName = $record.HostName
if ($hostName -ine "gc" -or "DomainDnsZones" -or "ForestDnsZones" -or "@") {
# Do some stuff
}
}
If I shorten it down to a single condition, it works but I want all conditions met:
if ($hostName -ine "gc")
If I expand out the statement so that each -or has explicit evaluations, it doesn't work:
if ($hostName -ine "gc" -or $hostName -ine "DomainDnsZones" -or $hostName -ine "ForestDnsZones" -or $hostName -ine "@") {
If I just use -ne, then it doesn't work for even a single record. I have a feeling that I'm missing something simple. I've tried trimming the string to exclude trailing spaces, but that didn't work either. String length matches what it should, so there's no extraneous space problems.
I've thought about nesting if statements, but that seems dumb. I have used the first example of chained -or conditions in other scripts without problem.
Thanks in advance!
Upvotes: 1
Views: 16702
Reputation: 47792
You should be using -and
to meet all conditions, and you must use the style of your second attempt where you have each comparison with its own left-hand operand:
if ($hostName -ine "gc" -and
$hostName -ine "DomainDnsZones" -and
$hostName -ine "ForestDnsZones" -and
$hostName -ine "@"
) { }
I would change it to use -notcontains
or -notin
:
if ("gc","DomainDnsZones","ForestDnsZones","@" -notcontains $hostname) { }
or
if ($hostname -notin "gc","DomainDnsZones","ForestDnsZones","@") { }
PowerShell is case-insensitive by default, but you can use -inotcontains
or -inotin
as well.
Upvotes: 2