[英]Powershell - strip all whitespace from each line in hosts file before creating variables from IP, FQDN & Hostname & using these to ping
Say we have a hosts file of: 假设我们有一个主机文件:
10.10.10.10 test1.domain test1
20.20.20.201 test2.domain test2
30.30.301.30 test3.domain test3
40.40.40.40 test4.domain test4
Note the IPs with 3 digits in the host identifier, with this in mind, each line is structured slightly differently, in that those with the 2 digits, have more spaces between the IP and the FQDN. 请注意主机标识符中具有3位数字的IP,请记住,每行的结构略有不同,因为具有2位数字的IP在IP和FQDN之间具有更多的空格。 Bearing in mind these differences, how would one either: 1. extract the FQDN from each line & ping as you go through each line OR 2. strip out the IP altogether and then loop through each entry, pinging each FQDN as you go?
牢记这些差异,怎么办:1.从每条线路中提取FQDN,并在遍历每条线路时执行ping操作;或2.完全剥夺IP,然后遍历每个条目,在执行过程中对每个FQDN进行ping操作?
I can't seem to do option 1, and the closest to option 2 I have got is by doing this: 我似乎无法执行选项1,最接近选项2的方法是:
Get-Content hosts | ForEach-Object { $_Split()[3]; }
But this only prints out those hosts where there is 3 digits in the host identifier, whilst those with 2 digits have more whitespace between the IP and FQDN, therefore it counts the FQDN as being on the 4th field. 但是,这只会打印出主机标识符中包含3位数字的那些主机,而那些具有2位数字的主机在IP和FQDN之间具有更大的空格,因此它将FQDN视为位于第4个字段。
Can anyone assist with this please? 有人可以帮忙吗? I am fairly new to PowerShell coming from a UNIX background.
我对来自UNIX背景的PowerShell相当陌生。
Strings in Powershell are .Net String objects and thus contain powerful manipulation methods. Powershell中的字符串是.Net字符串对象,因此包含强大的操作方法。
Split()
can be told to omit empty elements. 可以告诉
Split()
省略空元素。 Like so, 像这样
# Read host list
$data = Get-Content C:\Temp\hostlist.txt
# Split each row from the file. Use space to split, omit empty elements
# Thus element 0 is the IP, 1 is the FQDN, 2 is the hostname
$data | ForEach-Object { ($_.split(" ", [StringSplitOptions]::RemoveEmptyEntries))[1] }
# Output
test1.domain
test2.domain
test3.domain
test4.domain
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.