Saturday, August 23, 2014

Powershell - get all host files on domain.

Purpose: This script will search AD for Window computers and attempted to connect to each one. Then it will read the contents of the host file and write them to a csv file.

Note: This will take a while to run unless someone wants to make it multithreaded.
I just wrote this so there may need to be some bug fixes but in general it seemed to work.

#Read all host files and write to CSV file

Import-Module ActiveDirectory

$PATH = "c:\temp\hostfiles.csv"

   $myCol = @()
$AllComputers = Get-ADComputer -Filter {OperatingSystem -Like "Windows*"} -Property * | Select -Expand Name

foreach ($Computer in $AllComputers){

Write-Progress -activity "Scanning Machine $Computer " -status "Scanned: $i of $($AllComputers.Count)" -percentComplete (($i / $AllComputers.Count)  * 100)
 Get-Content -Path "\\$Computer\c$\windows\system32\drivers\etc\hosts" |             
 where {!$_.StartsWith("#")} |            
 foreach {            
  if ($_ -ne ""){            
  $data = $_ -split " ",2            
  $Hosts = New-Object -TypeName PSObject -Property @{            
     Host = $Computer
  IPAddress = $data[0].Trim()   
  Node = $data[1].Trim()            
  $myCol += $Hosts
 $myCol |Select Host,Node,IPAddress| Export-Csv -Path $PATH -NoTypeInformation

No comments:

Post a Comment