Powershell script to fetch IP address by pinging hostname

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.
Kailash KapalSenior ConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

becraigCommented:
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
Kailash KapalSenior ConsultantAuthor Commented:
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
Dale HarrisProfessional Services EngineerCommented:
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
David Johnson, CD, MVPOwnerCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dale HarrisProfessional Services EngineerCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.