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:- [System.Net.DNS]::GetHostByName('someName')
复制代码 With just a simple PowerShell wrapper, this is turned into a great little function that is extremely versatile:- function Get-IPAddress
- {
- param
- (
- [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
- [String[]]
- $Name
- )
-
- process
- { $Name | ForEach-Object { try { [System.Net.DNS]::GetHostByName($_) } catch { } }}
- }
复制代码 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.- Get-IPAddress
- Get-IPAddress -Name TobiasAir1
- Get-IPAddress -Name TobiasAir1, Server12, Storage1
- 'TobiasAir1', 'Server12', 'Storage1' | Get-IPAddress
- Get-QADComputer | Get-IPAddress
- 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 |