Looking for help to output the entries of localhost file of multiple servers in a csv file

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. Am a newbie

$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 the later

$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

welcome to the forums.

Please, when you post code or console output or error messages or sample data format it as code using the “preformatted text” button ( </> ).


If you want to reach another computer you have to tell PowerShell to reach the other computer. Either by PowerShell remoting …

$ComputerNameList = 'Red', 'Yellow', 'Blue', 'Green', 'White'
foreach ($ComputerName in $ComputerNameList) {
    Invoke-Command -ComputerName $ComputerName -ScriptBlock {
        Get-Content -Path "$env:windir\system32\drivers\etc\hosts" 
        Out-File -FilePath "C:\result\$($ComputerName)_hosts-file.txt"

… or with an UNC path.

foreach ($ComputerName in $ComputerNameList) {
    $Path = Join-Path -Path ('\\' + $ComputerName) -ChildPath 'C$\Windows\system32\drivers\etc\hosts'
    Get-Content -Path $Path | 
        Out-File -FilePath "C:\result\$($ComputerName)_hosts-file.txt"
Out-File : Could not find a part of the path 'C:\result\Red_hosts-file.txt'.
At C:\Users\user1\Documents\scripts\hostsfile.ps1:6 char:9
+         Out-File -FilePath "C:\result\$($ComputerName)_hosts-file.txt ...

Neither ran fine. I like the invoke-command but I was thinking a For where…condition …would catch the hosts file for each of the computers then output it.

You may create the folder for the results before you run the code. :wink:

You should learn how to read error messages and how to debug your PowerShell code in general.