Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Hosts File String Removal - Single Domain
- # Removes a certain line on every Non-Server Domain PC via UNC.
- # Run as Administrator
- # Gets search string to match in hosts file. Sets Hosts file names and Network Paths
- $Pattern = Read-Host -Prompt "Input Hosts File Search String"
- $HostsPath = '\C$\windows\System32\drivers\etc\'
- $TimeStamp = (Get-Date).ToString('yyyy-MM-dd_-_mm-ss')
- $OriHostsName = 'hosts'
- $HostsBakName = 'hosts_-_' + $Timestamp
- $TempHostsName = 'hosts2'
- $OriHostsFN = $HostsPath + $OriHostsName
- $TempHostsFN = $HostsPath + $TempHostsName
- # Gets List of Local Domain's Computers for all OUs. (Could add OU filter if req)
- $ComputerList = Get-ADComputer -filter { OperatingSystem -notLike '*Windows Server*' }
- ForEach ($Computer in $ComputerList)
- {
- # Gets Content of hosts file, assigns to var. Sets Out File Name/Path.
- $Content = Get-Content "\\$($Computer.Name)$($OriHostsFN)"
- $WriteFile = "\\$($Computer.Name)$($TempHostsFN)"
- # If the $Pattern matches, $Content proceed with changes.
- if ($Content -like "*$($Pattern)*")
- {
- # Writes all lines excluding those containing $Pattern to new file.
- $NewContent = $Content | Select-String -pattern $Pattern -notmatch
- [IO.File]::WriteAllLines($WriteFile,$NewContent)
- # Renames original hosts file, then renames our new file.
- Rename-Item -path "\\$($Computer.Name)$($OriHostsFN)" -newname $HostsBakName
- Rename-Item -path "\\$($Computer.Name)$($TempHostsFN)" -newname $OriHostsName
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment