Reputation: 505
I am retrieving the hosts file on a server with 5 DNS entries:
C:\Windows\System32\drivers\etc\hosts
Mine looks like this after the comments:
127.0.0.1 infspcpd8tx8e.rtmphost.com
127.0.0.1 infspkbpef39p.rtmphost.com
127.0.0.1 infspo99vn3ti.rtmphost.com
127.0.0.1 infspqx6l10wu.rtmphost.com
127.0.0.1 infspvdkqjhkj.rtmphost.com
In my hosts file I see them as 5 lines on top of eachother, but when I paste it here it has a space inbetween. This is the same when I use get-content on that file, but I wouldn't expect that to stop me.
So I have an array that is gotten like so: $ACCOUNTS = Get-ChildItem "D:\cyst\accounts\" | select name
I then try to see if there are duplicate entries in the hosts file by checking the $accounts variable against the array I got containing the hosts file.
foreach ($rtmp in $ACCOUNTS) {
$HostsFile = Get-Content C:\Windows\System32\drivers\etc\hosts | ForEach-Object {[System.Convert]::ToString($_)}
#$rt[string]$data = $HostsFile
[string]$rtmpfull = $rtmp.name + ".rtmphost.com"
if ($HostsFile -contains $rtmpfull) { Write-Host "Host found in hosts file moving on..." }
else { echo "wrong"
}
}
It never matches and always returns false, I can't match anything.. please help - is it a type issue? I've googled this for DAYS but now i'm desperate and posting here.
Upvotes: 0
Views: 18217
Reputation: 2621
$ACCOUNTS = Get-ChildItem "D:\cyst\accounts\"
foreach ($rtmp in $ACCOUNTS){
$found=$FALSE
foreach ($line in (gc C:\Windows\System32\drivers\etc\hosts)){
if(($line -match $rtmp) -and ($found -eq $TRUE)){
echo "$($matches[0]) is a duplicate"
}
if (($line -match $rtmp) -and ($found -eq $FALSE)){
echo "Found $($matches[0]) in host file..."
$found=$TRUE
}
}
}
Not elegant, but it will do the job.
Upvotes: 0
Reputation: 68273
I think you can probably speed that up by just dispensing with the foreach.
(Get-Content C:\Windows\System32\drivers\etc\hosts) -match [regex]::escape($rtmpfull)
Should match the entire hosts file at once.
Upvotes: 2
Reputation: 201672
This test:
if ($HostsFile -contains $rtmpfull)
is looking for $rtmpfull to match an entire line stored in $HostsFile. You want to check for a partial match like so;
if ($HostsFile | Foreach {$_ -match $rtmpfull})
BTW you can simplify this:
$HostsFile = Get-Content C:\Windows\System32\drivers\etc\hosts | ForEach-Object {[System.Convert]::ToString($_)}
to:
$HostsFile = Get-Content C:\Windows\System32\drivers\etc\hosts
By default, Get-Content will give you an array of strings where each element of the array corresponds to a line in the file.
Upvotes: 0