首页 > 解决方案 > 使用循环将多个文件的内容保存在别处

问题描述

我正在寻找从 5 台机器蓝色、绿色、黄色、白色、红色中获取文件主机信息,所有名称都存储在文件 C:\servers.csv 中。如何将输出保存在其他地方?到目前为止,这是我想出的:

$servernames = @(import-csv "C:\servers.csv")

foreach ( $servername in $servernames ) {
    Get-Content -Path "$env:windir\system32\drivers\etc\hosts" | Set-content C:\result.txt
}

我也试过这个:

$Computers = @("Red","Yellow","Blue","Green","White")

$File = "$env:windir\system32\drivers\etc\hosts"

foreach ($s in $Computers) { 
    Get-Content $File -Exclude localhost | set-content C:\result.txt
}

任何帮助,将不胜感激。

标签: powershell

解决方案


如果我正确理解您,您只想从与每台计算机相关的每个主机文件中获取内容,然后将其保存在其他地方?您可以采取这样的方法:

$Computers = @("Red","Yellow","Blue","Green","White")


foreach ($s in $Computers) {

    $Host_Content = Invoke-Command -ComputerName  $s -ScriptBlock {
        Get-Content -Path  "$env:windir\system32\drivers\etc\hosts"  | 
            ForEach-Object -Process { 
                $_ | Where-Object -FilterScript { $_ -notmatch "localhost" -and $_ -match "((?:(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d))" }
            }
    }

    $Host_Content 
    $Host_Content | Out-File -FilePath "C:\temp\$S.txt" -Force

}

这将允许您将每台计算机的主机文件内容保存到它自己的文本文件中,并使用它从中获取的相应计算机。

这只是圣地亚哥指出的问题。要么提供 UNC 路径,要么用于Invoke-Command将命令发送到远程 PC,完成工作,然后返回。我假设您不想要文件中的localhost条目,因此我将其排除在文件内容本身中。您还可以Get-DNSClientCache用于缓存的 dns 条目。

编辑:

添加了一些我在谷歌搜索中找到的正则表达式匹配,以将其缩小到只有 IP 的行


推荐阅读