如何从PowerShell中的文件中读取一行
我是 PowerShell 脚本的新手.我希望满足我的一项要求.
I am novice to the PowerShell scripting. I am looking to fulfill one of my requirement.
我有一个 hosts 文件,它有多个主机名和 IP 地址.下面是输入文件的例子.
I have one hosts file which is having multiple host names and IP addresses. Below is the example of the input file.
127.0.0.1 Host1 Host2 Host3
127.0.0.2 Host4 Host5 Host6
我想读取第一台主机 (Host1)、第二台主机 (Host2) 和第三台主机 (Host3) 的每一行和 ping.
I want to read each line and ping for the first host (Host1), then the second host (Host2) and then the third host (Host3).
在 ping 每个主机名时,我需要检查该主机的 ping 响应 IP 地址并将其与输入文件中提到的 IP 地址匹配.以下是我尝试使用上述格式读取文件的代码片段,但无法以这种方式工作.
While pinging each host name, I need to check the ping response IP address for that host and match it back with the IP address mentioned in the input file. Below is the snippet of code with which am trying to read the file in the above format, but it is not working in that way.
$lines = Get-Content myfile.txt
$lines |
ForEach-Object{
Test-Connection $_.Split(' ')[1]
}
谁能给我任何建议或在 PowerShell 脚本中为我提供一些东西?
Can anyone give me any advice or whip something in a PowerShell script for me?
尝试以下方法.应该很近了.
Try the following approach. It should be close.
$lines = Get-Content myfile.txt | Where {$_ -notmatch '^\s+$'}
foreach ($line in $lines) {
$fields = $line -split '\s+'
$ip = $fields[0]
$hosts = $fields[1..3]
foreach ($h in $hosts) {
$hostIP = (Test-Connection $h -Count 1).IPV4Address.ToString()
if ($hostIP -ne $ip) { "Invalid host IP $hostIP for host $h" }
}
}