Powershell to manipulate host file

后端 未结 9 1739
我在风中等你
我在风中等你 2021-01-30 02:32

I am looking at to see if I can create powershell script to update the contents in the host file.

Anybody know if there are any examples that manipulate the host file u

9条回答
  •  悲&欢浪女
    2021-01-30 03:05

    Starting with Kevin Remisoski's excellent answer above, I came up with this which lets me add/update multiple entries at once. I also changed the regex in the split to look for any white space, not just tab.

    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)
    

提交回复
热议问题