powershell - 使用循环将多个文件的内容保存在别处
问题描述
我正在寻找从 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
}
任何帮助,将不胜感激。
解决方案
如果我正确理解您,您只想从与每台计算机相关的每个主机文件中获取内容,然后将其保存在其他地方?您可以采取这样的方法:
$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 的行
推荐阅读
- java - 带有 Java 11 的 Arquillian Chameleon 容器
- android - 将应用设置为在单个通道上输出所有音频
- android - 使用 Camera2 API 为自定义相机捕获图像后尝试导航到下一个活动时,我的应用程序崩溃
- ios - 全选字符串数组 - Swift
- azure-devops - 尝试发布 SSAS 表格模型时出现 DevOps 错误
- ansible - ansible:AnsibleModule.log() 方法不会将任何内容打印到 stdout/stderr
- python-3.x - 不和谐 @bot.event 在 cog
- html - 嵌入式 Instagram 帖子的响应速度不够快
- python - Python:使用带有startswith的lambda
- android - 卡片的垂直列表视图 - 不正确的卡片被打开