Guest User

Hosts File String Removal - Single Domain

a guest
Jan 24th, 2017
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Hosts File String Removal - Single Domain
  2. # Removes a certain line on every Non-Server Domain PC via UNC.
  3. # Run as Administrator
  4.  
  5. # Gets search string to match in hosts file. Sets Hosts file Network Path
  6. $Pattern = Read-Host -Prompt "Input Hosts File Search String"
  7. $HostsPath = "\C$\windows\System32\drivers\etc\"
  8.  
  9.  
  10. # Gets Local Domain's Computer List for all OUs. (Could add filter if req)
  11. $Computers = Get-ADComputer -filter { OperatingSystem -notLike '*Windows Server*' }
  12. ForEach ( $Computer in $Computers)
  13. {
  14.  
  15.     # Adds contents of Text file which match $Pattern to $Content variable
  16.     $Content = Get-Content "\\$($Computer.Name)$($HostsPath)hosts" |
  17.         Select-String -pattern $Pattern
  18.      
  19. # Looped If Statement Per PC found in AD - Exits if $Pattern is not found
  20. if ( $Content -like "*$($Pattern)*")
  21.     {
  22.         # Reads content - Writes all Content but lines containing $Pattern to new File
  23.         Get-Content "\\$($Computer.Name)$($HostsPath)hosts" |
  24.             Select-String -pattern $Pattern -notmatch |
  25.             Out-File "\\$($Computer.Name)$($HostsPath)hosts2"
  26.        
  27.         # Renames original hosts file,  then renames our new file.
  28.         Rename-Item -path "\\$($Computer.Name)$($HostsPath)hosts" `
  29.             -newname "hosts-BAK-$((Get-Date).ToString('MM-dd-yyyy-hh-mm'))"
  30.         Rename-Item -path "\\$($Computer.Name)$($HostsPath)hosts2" -newname "hosts"
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment