2010-04-08 17 views
27

Sto cercando di vedere se posso creare lo script di PowerShell per aggiornare il contenuto nel file host.Powershell per manipolare il file host

Qualcuno sa se esistono esempi che manipolano il file host utilizzando PowerShell o qualsiasi altra lanuginatura di scripting?

Grazie.

+0

solo accodando al file (scrivendo ad esso, si dispone di autorizzazioni sufficienti) dovrebbe fare il trucco. – ChristopheD

risposta

26

Il primo, se siete su Vista o Windows 7 assicurarsi di eseguire questi comandi da un prompt elevata:

# 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 

Detto questo penso che si può vedere come usare una regex per manipolare le voci come necessario.

+0

Il non funziona funziona bene, ma i commenti stampano solo l'output [corretto] nella console, sto eseguendo lo script come amministratore, manca qualcosa? – veritas

+0

@veritas Sospetto che ci sia un problema con il modello regex. Va meglio? '^^S * ([^ #]. +? \ D {1,3}. *? Localhost. *)' ' –

+0

Ho scoperto che la variabile' $ hosts' non si aggiornava dopo 'foreach 'e semplicemente pipelined tutto l'output dopo foreach nel file:' $ hosts | foreach {...} | Out-File $ hostsPath -enc ascii' e funziona. – veritas

2

Ho scritto un codice per eliminare le voci dall'host. È possibile modificare facilmente il codice per aggiungere voci dal codice.

$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 
} 

Per ulteriori informazioni consultare http://nisanthkv.blog.com/2012/06/13/remove-host-entries-using-powershell/

+0

Non è necessario utilizzare html per inserire il codice, basta indentare il codice con 4 spazi. – Dhara

17

Il Carbon module ha una funzione Set-HostsEntry per impostare una voce nel file hosts:

Set-HostsEntry -IPAddress 10.2.3.4 -HostName 'myserver' -Description "myserver's IP address" 
0

Per me il più grande dolore nel trattare con il file hosts è ricordare dove è. Ho impostato una variabile che punta al mio file hosts nel mio profilo PowerShell, che semplifica la modifica in un editor di testo.

In PowerShell, digitare quanto segue per aprire il tuo profilo:

C:\> Notepad $profile 

Aggiungi questa:

$hosts = "$env:windir\System32\drivers\etc\hosts" 

Salvare il file, quindi chiudere e riaprire PowerShell, esecuzione come amministratore. Non è possibile modificare il file degli host senza autorizzazioni elevate.

Ora è possibile modificare i file host allo stesso modo che ci si modifichi il tuo profilo:

C:\> Notepad $hosts 
17

Se qualcuno è alla ricerca di un esempio più avanzato, sono sempre stato particolarmente affezionato a questo succo: https://gist.github.com/markembling/173887

# 
# Powershell script for adding/removing/showing entries to the hosts file. 
# 
# Known limitations: 
# - does not handle entries with comments afterwards ("<ip> <host> # comment") 
# 

$file = "C:\Windows\System32\drivers\etc\hosts" 

function add-host([string]$filename, [string]$ip, [string]$hostname) { 
    remove-host $filename $hostname 
    $ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename 
} 

function remove-host([string]$filename, [string]$hostname) { 
    $c = Get-Content $filename 
    $newLines = @() 

    foreach ($line in $c) { 
     $bits = [regex]::Split($line, "\t+") 
     if ($bits.count -eq 2) { 
      if ($bits[1] -ne $hostname) { 
       $newLines += $line 
      } 
     } else { 
      $newLines += $line 
     } 
    } 

    # Write file 
    Clear-Content $filename 
    foreach ($line in $newLines) { 
     $line | Out-File -encoding ASCII -append $filename 
    } 
} 

function print-hosts([string]$filename) { 
    $c = Get-Content $filename 

    foreach ($line in $c) { 
     $bits = [regex]::Split($line, "\t+") 
     if ($bits.count -eq 2) { 
      Write-Host $bits[0] `t`t $bits[1] 
     } 
    } 
} 

try { 
    if ($args[0] -eq "add") { 

     if ($args.count -lt 3) { 
      throw "Not enough arguments for add." 
     } else { 
      add-host $file $args[1] $args[2] 
     } 

    } elseif ($args[0] -eq "remove") { 

     if ($args.count -lt 2) { 
      throw "Not enough arguments for remove." 
     } else { 
      remove-host $file $args[1] 
     } 

    } elseif ($args[0] -eq "show") { 
     print-hosts $file 
    } else { 
     throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'." 
    } 
} catch { 
    Write-Host $error[0] 
    Write-Host "`nUsage: hosts add <ip> <hostname>`n  hosts remove <hostname>`n  hosts show" 
} 
+0

problemi di accesso temporaneo al file (bloccato). avviso se lo eseguo due volte, è spesso volte liberato. potrebbe essere buono per avvolgere i salvataggi in un tentativo. – sonjz

4

a partire dalla risposta eccellente di Kevin Remisoski sopra, mi si avvicinò con questo che mi permette di aggiungere/aggiornare più voci in una sola volta. Ho anche cambiato la regex nello split per cercare uno spazio bianco, non solo 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) 
+0

nice;) Dovrò giocarci, ho pensato che ultimamente non ho usato ambienti di tipo wamp. Beh, in realtà sono appena emigrato. Ho una macchina dual boot, ma essendo che sono rimasto bloccato in Windows per la maggior parte del tempo a causa delle mie altre esigenze, ho deciso di installare bash per Windows (basato su Ubuntu) e di capire quale molto meno dolore nella situazione del culo quando si riferisce alla migrazione da un ambiente Dev locale di Windows a una versione Dev o Live di Linux. –

Problemi correlati