Powershell to manipulate host file

后端 未结 9 1725
我在风中等你
我在风中等你 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 02:44

    First up, if you're on Vista or Windows 7 make sure you run these commands from an elevated prompt:

    # 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
    

    Given this I think you can see how to use a regex to manipulate entries as necessary.

提交回复
热议问题