回复 9# idwma
老外的代码参考:- # Uncomment lines with localhost on them:
- $hostsPath = "$env:windir\System32\drivers\etc\hosts"
- $hosts = get-content $hostsPath
- $hosts = $hosts | Foreach {if ($_ -match '^\s*#\s*(.*?\d{1,3}.*?localhost.*)')
- {$matches[1]} else {$_}}
- $hosts | Out-File $hostsPath -enc ascii
-
- # Comment lines with localhost on them:
- $hosts = get-content $hostsPath
- $hosts | Foreach {if ($_ -match '^\s*([^#].*?\d{1,3}.*?localhost.*)')
- {"# " + $matches[1]} else {$_}} |
- Out-File $hostsPath -enc ascii
复制代码 ------------------------------------------------------------------------------------------------ function setHostEntries([hashtable] $entries) {
- $hostsFile = "$env:windir\System32\drivers\etc\hosts"
- $newLines = @()
-
- $c = Get-Content -Path $hostsFile
- foreach ($line in $c) {
- $bits = [regex]::Split($line, "\s+")
- if ($bits.count -eq 2) {
- $match = $NULL
- ForEach($entry in $entries.GetEnumerator()) {
- if($bits[1] -eq $entry.Key) {
- $newLines += ($entry.Value + ' ' + $entry.Key)
- Write-Host Replacing HOSTS entry for $entry.Key
- $match = $entry.Key
- break
- }
- }
- if($match -eq $NULL) {
- $newLines += $line
- } else {
- $entries.Remove($match)
- }
- } else {
- $newLines += $line
- }
- }
-
- foreach($entry in $entries.GetEnumerator()) {
- Write-Host Adding HOSTS entry for $entry.Key
- $newLines += $entry.Value + ' ' + $entry.Key
- }
-
- Write-Host Saving $hostsFile
- Clear-Content $hostsFile
- foreach ($line in $newLines) {
- $line | Out-File -encoding ASCII -append $hostsFile
- }
- }
-
- $entries = @{
- 'aaa.foo.local' = "127.0.0.1"
- 'bbb.foo.local' = "127.0.0.1"
- 'ccc.foo.local' = "127.0.0.1"
- };
- setHostEntries($entries)
复制代码 --------------------------------------------------------------- $domainName = "www.abc.com"
- $rplaceStr = ""
- $rHost = "C:\Windows\System32\drivers\etc\hosts"
- $items = Get-Content $rHost | Select-String $domainName
- Write-host $items
- foreach( $item in $items)
- {
- (Get-Content $rHost) -replace $item, $rplaceStr| Set-Content $rHost
- }
复制代码
|