Solved

Powershell script to fetch IP address by pinging hostname

Posted on 2014-09-03
6
4,546 Views
Last Modified: 2014-09-12
I want a powershell script for fetching IP address and outputting it into csv / text file by pinging hostname

I would also like other server details as well.
0
Comment
Question by:Kailash Kapal
6 Comments
 
LVL 28

Expert Comment

by:becraig
ID: 40302341
Can you indicate all the details you need ?

$servers | % {
$server = $_
$ipaddr = gwmi -class Win32_NetworkAdapterConfiguration -computername $server -filter 'IPEnabled="True"' | select -expand IPAddress | ?{$_ -notmatch ':'} 
}

Open in new window

0
 

Author Comment

by:Kailash Kapal
ID: 40302422
I want  IP address, OS version to be pulled in a csv file

I wanted the hostnames to be put via an excel or text file in the powershell script

Also i would want the flexibility to add more details as and when required in future.

Hope that helps.
0
 
LVL 16

Expert Comment

by:Dale Harris
ID: 40311452
Here is a script I made for our environment that talks about the various ways you can get the data remotely (You must run the script as an administrator and have Quest CMDLets installed (http://www.quest.com/powershell/activeroles-server.aspx)

Clear-Host
$Computer = Read-Host "Enter the Computer Name (Partial is okay) you want to lookup"
$PC = Get-QADComputer "*$Computer*"
if ($PC -eq $null){
Write-Host "Host not found in AD" -foregroundcolor Yellow
}
else
{
""
""
$BIOS = gwmi win32_bios -computer $PC.name
$ComputerSystem = gwmi win32_ComputerSystem -computer $PC.Name
Write-Host "Computer Name: $($PC.name)" -foregroundcolor yellow
"Serial Number: $($BIOS.serialnumber)"
"Description: $($PC.Description)"
"Network: NIPR"
$IP = gwmi -class Win32_NetworkAdapterConfiguration -computername $PC.name -filter 'IPEnabled="True"' | select -expand IPAddress | ?{$_ -notmatch ':'} 
"Location: Building $($IP.split(".")[2])"
"Manufacturer: $($BIOS.manufacturer)"
"Model: $($ComputerSystem.model)"
"Managed by: $($PC.ManagedBy)"
"OS:$($PC.OSName)"
"OU: $(($PC.dn.split(",")[2]).split("=")[1])"
"IP Address: $IP"
"MAC Address: $((gwmi -Class Win32_NetworkAdapterConfiguration -Computername $PC.name | where { $_.IpAddress -eq $IP}).MACAddress)"
"Primary User: $($ComputerSystem.username)"
""
Write-Host "Pinging Computer for response:" -foregroundcolor Yellow
Ping $($PC.name) -n 2
""
""
}
$Pause = Read-Host "Press enter to continue"

Open in new window


If you want to do the script that does it based on a list, you can modify it to the following script:

$List = gc .\list.txt
foreach ($Computer in $List){
$PC = Get-QADComputer "*$Computer*"
	if ($PC -eq $null){
		Write-Host "$Computer match not found in AD" -foregroundcolor Yellow
	}
	else
	{
		""
		""
		$BIOS = gwmi win32_bios -computer $PC.name
		$ComputerSystem = gwmi win32_ComputerSystem -computer $PC.Name
		Write-Host "Computer Name: $($PC.name)" -foregroundcolor yellow
		"Serial Number: $($BIOS.serialnumber)"
		"Description: $($PC.Description)"
		"Network: NIPR"
		$IP = gwmi -class Win32_NetworkAdapterConfiguration -computername $PC.name -filter 'IPEnabled="True"' | 		select -expand IPAddress | ?{$_ -notmatch ':'} 
		"Location: Building $($IP.split(".")[2])"
		"Manufacturer: $($BIOS.manufacturer)"
		"Model: $($ComputerSystem.model)"
		"Managed by: $($PC.ManagedBy)"
		"OS:$($PC.OSName)"
		"OU: $(($PC.dn.split(",")[2]).split("=")[1])"
		"IP Address: $IP"
		"MAC Address: $((gwmi -Class Win32_NetworkAdapterConfiguration -Computername $PC.name | where { 				$_.IpAddress -eq $IP }).MACAddress)"
		"Primary User: $($ComputerSystem.username)"
		""
	}#end if
}#end for loop

Open in new window


If you want to output that to a CSV, you can easily convert the above with an online way to write to an excel file
http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/23/use-powershell-to-work-with-csv-formatted-text.aspx

Personally, I like to output to a text file separated by semicolons, and import it into excel and separate by semicolon

That would take a big rework for that to happen, but it's not impossible.  It's ugly for code though.  You would first capture all of the output to variables instead of output lines.  Then you would add that to your output list.
0
 
LVL 78

Accepted Solution

by:
David Johnson, CD, MVP earned 250 total points
ID: 40311509
from powershell use the following

get-content -path c:\powershell\servers.txt | .\get-ipaddress.ps1  -ipv4only
function global:Get-IPAddress { 
#Requires -Version 2.0             
[CmdletBinding()]             
 Param              
   (                        
    [Parameter(Position=1, 
               ValueFromPipeline=$true, 
               ValueFromPipelineByPropertyName=$true)] 
    [String[]]$ComputerName = $env:COMPUTERNAME, 
    [Switch]$IPV6only, 
    [Switch]$IPV4only 
   )#End Param 
 
Begin             
{             
 Write-Verbose "`n Checking IP Address . . .`n" 
 $i = 0             
}#Begin           
Process             
{ 
    $ComputerName | ForEach-Object { 
        $HostName = $_ 
 
        Try { 
            $AddressList = @(([net.dns]::GetHostEntry($HostName)).AddressList) 
        } 
        Catch { 
            "Cannot determine the IP Address on $HostName" 
        } 
 
        If ($AddressList.Count -ne 0) 
        { 
            $AddressList | ForEach-Object { 
            if ($IPV6only) 
                { 
                    if ($_.AddressFamily -eq "InterNetworkV6") 
                        { 
                            New-Object psobject -Property @{ 
                                IPAddress    = $_.IPAddressToString 
                                ComputerName = $HostName 
                                } | Select ComputerName,IPAddress    
                        } 
                } 
            if ($IPV4only) 
                { 
                    if ($_.AddressFamily -eq "InterNetwork") 
                        { 
                              New-Object psobject -Property @{ 
                                IPAddress    = $_.IPAddressToString 
                                ComputerName = $HostName 
                               } | Select ComputerName,IPAddress    
                        } 
                } 
            if (!($IPV6only -or $IPV4only)) 
                { 
                      New-Object psobject -Property @{ 
                        IPAddress    = $_.IPAddressToString 
                        ComputerName = $HostName 
                       } | Select ComputerName,IPAddress 
                } 
        }#IF 
        }#Foreach-Object(IPAddress) 
    }#Foreach-Object(ComputerName) 
 
}#Process 
 }

Open in new window


http://gallery.technet.microsoft.com/scriptcenter/44e9fef7-a04b-40b3-bb05-97659e56e27e
0
 
LVL 16

Assisted Solution

by:Dale Harris
Dale Harris earned 250 total points
ID: 40311527
As this actually helps our organization, I made the followup script to the one I posted on outputting into a text file with semicolon delineated columns for each specific part of info.  Also, I don't like when it pops up red for being offline, so half of the data is pulled if it's online to speed it up.  It did 132 computers in about 5 minutes.

I also cleaned up IP addresses so it didn't pull 169 addresses on a secondary adapter (happened to one of our computers upon testing).  I took the list from Active Directory and exported into "List.txt" by computer name only (modify columns allows you to see only computer name if you'd like).  It imports List.txt and runs through them all with a counter.  Each time the script runs, it overwrites the same file, so be careful to save your data before rerunning the script on a different list.  You can easily add a get-date to the name so it becomes unique, but that's messier if you don't clean up your stuff.

$List = gc .\list.txt
"PCName;SN;Description;Network;IP;Location;Manufacturer;Model;ManagedBy;OS;OU;MAC;User" > Computerinfo.txt
$Total = $List.count
$i = 0
foreach ($Computer in $List){
$PC = Get-QADComputer "*$Computer*"
$i++
"Searching for $($PC.name)... ($i of $Total)"
	if ($PC -eq $null){
		#The computer is not in AD, so skip it
		Write-Host "$Computer match not found in AD" -foregroundcolor Yellow
	}
	else
	{
		#Part of the info needs the host to be online, the other info is in AD
		if (Test-Connection $PC.name -count 1 -quiet){
			Write-Host "$($PC.Name) Online.  Please wait..." -foregroundcolor Green
			$BIOS = gwmi win32_bios -computer $PC.name
			$ComputerSystem = gwmi win32_ComputerSystem -computer $PC.Name
			$IP = gwmi -class Win32_NetworkAdapterConfiguration -computername $PC.name -filter 'IPEnabled="True"' | select -expand IPAddress | ?{$_ -notlike "169*"} 
			$Location = $IP.split(".")[2]
			$Manufacturer = $BIOS.manufacturer
			$Model = $ComputerSystem.model.trim()
			$SN= $BIOS.serialnumber
			$MAC = (gwmi -Class Win32_NetworkAdapterConfiguration -Computername $PC.name | ? { $_.IpAddress -eq $IP }).MACAddress
			$User = $ComputerSystem.username
		}
		else
		{
			#Put null values for each item above
			Write-host "$($PC.Name) is offline." -foregroundcolor Red
			$BIOS = ""
			$ComputerSystem = ""
			$IP = ""
			$Location = ""
			$Manufacturer = ""
			$Model = ""
			$SN = ""
			$MAC = ""
			$User = ""
		}#end if
		$PCName=$PC.name
		$Description = $PC.Description
		$Network = "NIPR"
		$Managedby = $PC.ManagedBy
		$OS = $PC.OSName
		$OU = ($PC.dn.split(",")[2]).split("=")[1]
		#Output all into a text file called ComputerInfo.txt
		"$PCName;$SN;$Description;$Network;$IP;$Location;$Manufacturer;$Model;$ManagedBy;$OS;$OU;$MAC;$User" >> Computerinfo.txt
	}#end if
}#end for loop

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Short answer to this question: there is no effective WiFi manager in iOS devices as seen in Windows WiFi or Macbook OSx WiFi management, but this article will try and provide some amicable solutions to better suite your needs.
Utilizing an array to gracefully append to a list of EmailAddresses
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now