Powershell—在从IP、FQDN&;创建变量之前,请删除主机文件中每一行的所有空白;主机名&;使用这些来ping
假设我们有一个主机文件:Powershell—在从IP、FQDN&;创建变量之前,请删除主机文件中每一行的所有空白;主机名&;使用这些来ping,powershell,split,string-matching,Powershell,Split,String Matching,假设我们有一个主机文件: 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 请注意主机标识符中有3位数字的IP,记住这一点,每行的结构略有不同,即有2位数字的IP和FQDN之间有更多的空格。 考虑到这些差异,如何: 1.从每行中提取FQDN,并在遍历每行时ping 或 2.完
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
请注意主机标识符中有3位数字的IP,记住这一点,每行的结构略有不同,即有2位数字的IP和FQDN之间有更多的空格。
考虑到这些差异,如何:
1.从每行中提取FQDN,并在遍历每行时ping
或
2.完全剥离IP,然后循环遍历每个条目,在执行时ping每个FQDN
我似乎不能做选项1,而我得到的最接近选项2的方法是这样做:
Get-Content hosts | ForEach-Object { $_Split()[3]; }
但这只打印出主机标识符中有3位数字的主机,而有2位数字的主机在IP和FQDN之间有更多的空白,因此它将FQDN计算在第4个字段上
有人能帮忙吗?我是来自UNIX背景的PowerShell新手。PowerShell中的字符串是.Net字符串对象,因此包含强大的操作方法。可以被告知是元素。这样,
# 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