この記事は2008/02/19にわんくまブログで書いたものです。
今日は、PowerShellでホスト名とIPアドレスを相互変換する関数を作ってみました。
まずはIPアドレスからホスト名を取得する関数です
Get-HostByName.ps1
#=============================================================================== # Get-HostByName: IPアドレスからホスト名を取得する # # 使用例 # PS > Get-HostByName 10.84.5.10 # # copyright HIRO's.NET(http://hiros-dot.net/) #=============================================================================== [void][reflection.assembly]::LoadWithPartialName("System.Net") function global:Get-HostByName { Param ([string]$IPAddress) $hostEntry = New-Object System.Net.IPHostEntry $hostEntry = [System.Net.Dns]::GetHostEntry($IPAddress) return $hostEntry.HostName }
ポイント
IPアドレスからホスト名を取得するのに、System.Net.DnsのGetHostEntryメソッドを使用しています。
HostEntry情報を取得したら、その中のHostNameプロパティを参照し、ホスト名を取得します。
次にホスト名からIPアドレスを取得する関数です。
Get-HostByAddress.ps1
#=============================================================================== # Get-HostByAddress: ホスト名からIPアドレスを取得する # # 使用例 # PS > Get-HostByAddress "www.yahoo.co.jp" # # copyright HIRO's.NET(http://hiros-dot.net/) #=============================================================================== [void][reflection.assembly]::LoadWithPartialName("System.Net") function global:Get-HostByAddress { Param ([string]$HostName) $hostEntry = New-Object System.Net.IPHostEntry $hostEntry = [System.Net.Dns]::GetHostEntry($HostName) return $hostEntry.AddressList[0].IPAddressToString }
こちらもSystem.Net.DnsのGetHostEntryメソッドを使用しています。
HostEntry情報を取得したら、その中のAddressList(配列で返されます)を取得し、IPAddressToString でIPアドレスのみを取得しています。
Theme design by Jelle Druyts
Pick a theme: BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2 BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009, HIRO
E-mail