如何使用 PowerShell 更新 Windows 主機檔案條目?
假設你要更新 host 檔案的特定條目,我們的本地計算機中有以下 host 檔案。
示例
Get-Content $env:windir\system32\drivers\etc\hosts
輸出
# For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost 8.8.8.8 Google.com
我們需要將 google.com 條目更新為 IP 地址 4.4.4.4。
示例
$hostfile = "$env:windir\system32\drivers\etc\hosts" $file = Get-Content $hostfile $newfile = $file -replace "8.8.8.8 Google.com","4.4.4.4 Google.com" Set-Content -Value $newfile -Path $hostfile -Force
再次檢查 host 檔案後,會顯示一個新條目。
若要在遠端計算機上更新 host 檔案,只需更改$hostfile變數位置,其餘內容保持不變。
$hostfile = "\RemoteServer\C$\Windows\system32\drivers\etc\hosts"
廣告