Board logo

标题: [转载代码] [PowerShell每日技巧]根据主机名获取IP地址(20140128) [打印本页]

作者: DAIC    时间: 2014-2-12 11:14     标题: [PowerShell每日技巧]根据主机名获取IP地址(20140128)

There is a tiny .NET function called GetHostByName() that is vastly useful. It will look up a host name and return its current IP address:
  1. [System.Net.DNS]::GetHostByName('someName')
复制代码
With just a simple PowerShell wrapper, this is turned into a great little function that is extremely versatile:
  1. function Get-IPAddress
  2. {
  3.   param
  4.   (
  5.     [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
  6.     [String[]]
  7.     $Name
  8.   )
  9.   process
  10.   { $Name | ForEach-Object { try { [System.Net.DNS]::GetHostByName($_) } catch { } }}
  11. }
复制代码
You can now run the function as-is (to get your own IP address). You can submit one or more computer names (comma separated). You can even pipe in data from Get-ADComputer or Get-QADComputer.
  1. Get-IPAddress
  2. Get-IPAddress -Name TobiasAir1
  3. Get-IPAddress -Name TobiasAir1, Server12, Storage1
  4. 'TobiasAir1', 'Server12', 'Storage1' | Get-IPAddress
  5. Get-QADComputer | Get-IPAddress
  6. Get-ADComputer -Filter * | Get-IPAddress
复制代码
This is possible because the function has both a pipeline binding and an argument serializer.

The -Name argument is fed to ForEach-Object, so no matter how many computer names a user specifies, they all get processed.

The -Name parameter accepts value from the pipeline both by property and as a value. So you can feed in any object that has a "Name" property, but you can also feed in any list of plain strings.

Note that the function has a very simple error handler. If you submit a computer name that cannot be resolved, nothing happens. Add code to the catch block if you want an error message instead.

http://powershell.com/cs/blogs/tips/archive/2014/01/28/getting-dns-ip-address-from-host-name.aspx
作者: ycxb0315    时间: 2014-2-12 15:56

有没有if的教程,谢谢!
作者: ivor    时间: 2014-2-12 16:08

  1. http://marui.blog.51cto.com/1034148/293907
复制代码
多百度
作者: DAIC    时间: 2014-2-12 16:25

回复 2# ycxb0315


http://www.bathome.net/thread-26167-1-1.html




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2