Mike
Mike

Reputation: 9

Save content of multiple files elsewhere using a loop

I am looking to grab the file host info from 5 machines Blue,Green,Yellow,White,Red all names stored in a file C:\servers.csv. How can I get the output saved somewhere else? So far this is what I have come up with:

$servernames = @(import-csv "C:\servers.csv")

foreach ( $servername in $servernames ) {
    Get-Content -Path "$env:windir\system32\drivers\etc\hosts" | Set-content C:\result.txt
}

I also tried this:

$Computers = @("Red","Yellow","Blue","Green","White")

$File = "$env:windir\system32\drivers\etc\hosts"

foreach ($s in $Computers) { 
    Get-Content $File -Exclude localhost | set-content C:\result.txt
}

Any help would be appreciated.

Upvotes: 0

Views: 70

Answers (2)

Abraham Zinala
Abraham Zinala

Reputation: 4694

If i'm understanding you corretcly, you just want to grab the content from within each host file pertaining to each computer, then save it else where? You can take an approach like so:

$Computers = @("Red","Yellow","Blue","Green","White")


foreach ($s in $Computers) {

    $Host_Content = Invoke-Command -ComputerName  $s -ScriptBlock {
        Get-Content -Path  "$env:windir\system32\drivers\etc\hosts"  | 
            ForEach-Object -Process { 
                $_ | Where-Object -FilterScript { $_ -notmatch "localhost" -and $_ -match "((?:(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d))" }
            }
    }

    $Host_Content 
    $Host_Content | Out-File -FilePath "C:\temp\$S.txt" -Force

}

This will allow you to save the host files content from each computer into it's own text file with the corresponing computer it got it from.

It's just a matter of what Santiago pointed out. Either provide the UNC path, or use Invoke-Command to send the command over to the remote PC, do the work, and return it. I assumed you didn't want the localhost entries from the files so I excluded it in the file content itself. You can also use Get-DNSClientCache for cached dns entries.

EDIT:

Added some regex matching I found on a google search to narrow it down to lines with just IPs

Upvotes: 3

boysenberry12
boysenberry12

Reputation: 1

Are you trying to get the info from a unc path?

$Computers = @("Red","Yellow","Blue","Green","White")

foreach ($computer in $Computers) { 
    Get-Content "\\$computer\c`$\windows\system32\drivers\etc\hosts" -Exclude localhost | set-content C:\result.txt
}

Upvotes: -1

Related Questions