在Powershell中使用nslookup获取主机名的IP地址 [英] Getting IP addresses for hostnames using nslookup in Powershell

查看:656
本文介绍了在Powershell中使用nslookup获取主机名的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Powershell脚本的新手,我需要编写一个脚本。我有一个服务器主机名列表,我需要获取这些服务器的IP地址并将结果写入文件。

I am new to Powershell scripting and I need to write one script. I have a list of server hostnames and I need to get IP addresses of those servers and write the results in a file.

主机名是Excel电子表格中的一列,但我可以将它们格式化为任何东西(csv,每行有一个主机名的简单txt文件等)。

The hostnames are one column in Excel spreadsheet but I can format them into anything (csv, simple txt file with one hostname per line etc.).

我想按照主机名的方式格式化输出服务器及其每行IP地址(因此,如果服务器有多个IP,则有多行)。

I would like to format the output the way there is a hostname of the server and its IP address per line (so there are multiple lines in case the server has more than one IP).

到目前为止,我一直在使用简单的文本文件每行的主机名,但从PS的输出我无法区分IP地址的服务器。

So far I have been using the simple text file with hostname per line, but from the output in PS I am unable to distinguish what server the IP address is for.

$servers = get-content "path_to_the_file" 
foreach ($server in $servers) {
[System.Net.Dns]::GetHostAddresses($server)
}

所以我想知道从csv文件加载主机名并再次将主机名和相关的IP地址打印到另一个csv,但我不确定

So I was wondering about loading the hostnames from csv file and printing the hostnames and related IP addresses to another csv again, but I am unsure how.

我正在研究通过在foreach中运行nslookup $ server来捕获所需信息(主机名和IP)的可能性。

I am investigating the possibility to capture the required information (hostname and IP) by running nslookup $server in foreach.

可能有人帮我一把吗?

谢谢。

推荐答案

组合地址的主机名可以在循环内完成。由于主机可以有多个IP地址,因此您也需要将其设置为accout。这将创建另一个循环。像这样,

Combining hostnames to addresses can be done within the loop. As a host can have multiple IP addresses, you need to take that into accout too. This will create another a loop. Like so,

$servers = get-content "path_to_the_file"
foreach ($server in $servers) {
  $addresses = [System.Net.Dns]::GetHostAddresses($server)
  foreach($a in $addresses) {
    "{0},{1}" -f $server, $a.IPAddressToString
  }
}

这篇关于在Powershell中使用nslookup获取主机名的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆