Guest User

Untitled

a guest
Jan 25th, 2017
252
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 names and Network Paths
  6. $Pattern = Read-Host -Prompt "Input Hosts File Search String"
  7. $HostsPath = '\C$\windows\System32\drivers\etc\'
  8. $TimeStamp = (Get-Date).ToString('yyyy-MM-dd_-_mm-ss')
  9.  
  10. $OriHostsName = 'hosts'
  11. $HostsBakName = 'hosts_-_' + $Timestamp
  12. $TempHostsName =  'hosts2'
  13.  
  14. $OriHostsFN = $HostsPath + $OriHostsName
  15. $TempHostsFN = $HostsPath + $TempHostsName
  16.  
  17. # Gets List of Local Domain's Computers for all OUs. (Could add OU filter if req)
  18. $ComputerList = Get-ADComputer -filter { OperatingSystem -notLike '*Windows Server*' }
  19.  
  20. ForEach ($Computer in $ComputerList)
  21. {
  22.     # Gets Content of hosts file, assigns to var. Sets Out File Name/Path.
  23.     $Content = Get-Content "\\$($Computer.Name)$($OriHostsFN)"
  24.     $WriteFile = "\\$($Computer.Name)$($TempHostsFN)"
  25.    
  26.     # If the $Pattern matches, $Content proceed with changes.
  27.     if ($Content -like "*$($Pattern)*")
  28.     {
  29.         # Writes all lines excluding those containing $Pattern to new file.
  30.         $NewContent = $Content | Select-String -pattern $Pattern -notmatch
  31.         [IO.File]::WriteAllLines($WriteFile,$NewContent)
  32.        
  33.         # Renames original hosts file,  then renames our new file.
  34.         Rename-Item -path "\\$($Computer.Name)$($OriHostsFN)" -newname $HostsBakName
  35.         Rename-Item -path "\\$($Computer.Name)$($TempHostsFN)" -newname $OriHostsName
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment