【问题标题】:Edit hosts file using powershell script使用 powershell 脚本编辑主机文件
【发布时间】:2022-10-14 03:49:22
【问题描述】:

我想创建 powershell 脚本来检测机器的 ip 地址,例如 10.10.10.2,然后查看 hosts 文件,如果有不同的 ip 地址,例如:

10.10.20.5 - test1env.test.loc
10.10.20.6 - test2env.test.loc
10.10.20.7 - test3env.test.loc
10.10.20.8 - test4env.test.loc

那么它应该用它当前的 IP 地址第三列号替换第三列号,它应该在脚本运行后看起来像这样:

10.10.10.5 - test1env.test.loc
10.10.10.6 - test2env.test.loc
10.10.10.7 - test3env.test.loc
10.10.10.8 - test4env.test.loc

是否可以创建执行此操作的脚本?

【问题讨论】:

  • 是的,这是可能的。
  • 欢迎来到 StackOverflow。请向我们展示您自己尝试过的内容。注意这是不是一个脚本工厂。您需要自己编写脚本。如果您遇到现有问题和答案尚未涵盖的问题,您可以在此处发布您的minimal reproducible example,以便我们能够进一步帮助您。另见:How to ask a good question

标签: powershell


【解决方案1】:

您可以通过读取文件并替换所述条目来实现此目的。替换它的整个开头而不是仅替换一部分可能更容易。假设专用网络也可以更改为 172.16,即使在这种情况下也可以正常工作。

要实现您想要做的事情,您可能需要:

  • 获取 IP 的方法(例如Powershell get ipv4 address into a variable
  • 一种读取文件的方法 (Get-Content)
  • 一种替换字符串的方法(例如 -replace,参见 about_Comparison_Operators)
  • 一种写入该文件的方法(Set-Content 或 Out-File 可以)

伪代码可能如下所示:

$ip = findIPs()
$hosts = Get-Content hosts
$oldip = findOldIP($hosts)
$hosts -replace $oldip,$ip | Set-Content hosts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2013-07-08
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多