Powershell get IPs from hosts programmatically - powershell

I have a list of hosts from my LAN (over 1000) that was extracted in Excel format from previous guy that worked here before I started my employment. I need to know the IP's of each host.
I would need some automatic extract (I hope there should be a smarter method than to ping manually all hosts in order to get the IP). I came across SO and read this question. Using PowerShell means a good step toward automation of what I need.
However, at what I am stuck is how to automate this command (in PowerShell) in order to use the excel file as input (or text) and provide an output file that contains the relevant IPs?
Update: a code I have in mind:
$servers = get-content "C:\scr\Servers.txt"
foreach ($Server in $Servers)
{
$Addresses = $null
try {
$Addresses = [System.Net.Dns]::GetHostAddresses("$Server").IPAddressToString
}
catch {
$Addresses = "Server IP cannot resolve."
}
foreach($Address in $addresses) {
write-host $Server, $Address
}
}
The Excel file used as input contains line by line the hostnames in a single column. This Excel file could be easily converted to text format (which is what I already done by now, resulting the Servers.txt file).
The problem with this code is that it displays the output only in the Powershell window, no file.

$output = #()
$servers = get-content "C:\scr\Servers.txt"
foreach ($Server in $Servers)
{
$Addresses = $null
try {
$Addresses = ((Test-Connection $Server | select -skip 3).IPV4Address).IPAddressToString
}
catch {
$Addresses = "Server IP cannot resolve."
}
$output += New-object psobject -property #{
servername = $server
Addresses = $Addresses
}
}
$output | select servername, Addresses | export-csv ".\Addresslist.csv" -NoTypeInformation

Finally, this code has worked successfuly, after tweakening (and also displays in the Powershell windows its outcome - those IPs - during script's execution). At the end, the results are exported in the Addresslist.csv file.
$output = #()
$servers = get-content "C:\scr\Servers.txt"
foreach ($Server in $Servers)
{
$Addresses = $null
try {
$Addresses = [System.Net.Dns]::GetHostAddresses("$Server")
}
catch {
$Addresses = "Server IP cannot resolve."
}
$output += New-object psobject -property #{
servername = $server
Addresses = $Address
}
foreach($Address in $addresses) {
write-host $Server, $Address
}
}
$output | select servername, Addresses | export-csv ".\Addresslist.csv" -NoTypeInformation

Related

Unable to export the data to CSV or Excel

I have written a script to check the nslookup for each server and export the details to Excel, but my script is looking but I am not able to export the output when I export I a getting empty data.
Please help me to export the data to Excel
CODE
## Loop through each server for Nslookup
foreach ($Server in $Servers)
{
$Addresses = $null
try {
$Addresses = [System.Net.Dns]::GetHostAddresses("$Server").IPAddressToString
}
catch {
$Addresses = "Server IP cannot resolve"
}
foreach($Address in $addresses) {
#write-host $Server, $Address
$Server_Name = $Server
$IP_Address = $Address
}
}
$result | Export-Excel -Path $FileName -AutoSize -BoldTopRow -FreezeTopRow -TitleBold -WorksheetName Server_Nslookup_Details
Your inner foreach loop is producing no output, just assigning values to the 2 variables ($Server_Name and $IP_Address):
foreach($Address in $addresses) {
$Server_Name = $Server
$IP_Address = $Address
}
You likely meant to construct a new object instead:
$result = foreach($Server in $Servers) {
$addresses = try {
[System.Net.Dns]::GetHostAddresses($Server).IPAddressToString
}
catch {
"Server IP cannot resolve"
}
foreach($address in $addresses) {
[pscustomobject]#{
Server = $Server
IPAddress = $address
}
}
}
$result | Export-Excel ....

How to Scan multiple Hostnames to resolve Ip addresses Powershell script

I am looking for some help with a script that will read a textfile full of server names and resolve the IP address and export this into a csv file. I am using powershell for this and the Test-Connection command. Please see below code - i am getting the error - cmdlet ForEach-Object at command pipeline position 1 Supply values for the following parameters:Process[0]:
(removed my username and swapped with ***)
$array=#()
$computer=Get-Content -Path c:\Users\****\Desktop\ping_IP_host\computers.txt
ForEach ($server in $computer){
if(Test-Connection $server -Quiet)
{
try {
$IP=
[System.net.dns]::GetHostEntry($server).AddressList | %
{$_.IpAddressTostring}
}
catch {"Invalid HostName" - $server}
$obj = New-Object PSObject -Property #{
Hostname=$server
IP=$IP
}
$array += $obj
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname=$server
IP=$IP
}
$array += $obj
}
}
$array | Export-Csv C:\Users\****\Desktop\ping_IP_host\results.csv
There is a misplace curly bracket, duplicated code, logic error and unwrapped objects.
Indenting properly will help you to find errors and duplicated code.
The custom object you build does contain both IPv4 and IPv6 addresses, so you may want to join the 2 addresses OR just select the IPv4 address - I do not know your requirements.
Edit:
The try..catch block is not needed as it depends on GetHostEntry() getting a result for the DNS lookup of $server, which is already verified by the test-connection. In short, your code defaults to the else clause "Invalid Host" when the host does not exist OR the host does not answer to ICMP.
the try..catch block around $IP = ([System.net.dns]::GetHostEntry($server).AddressList should be located before the Test-Connection because an error means the host name is invalid so no point in trying a ping.
Note: The code below does not take into account the above edit.
Working code:
$array=#()
$computer=Get-Content -Path $env:userprofile\Desktop\ping_IP_host\computers.txt
ForEach ($server in $computer) {
if (Test-Connection $server -Quiet -count 1) {
try {
$IP = ([System.net.dns]::GetHostEntry($server).AddressList | ForEach-Object {$_.IPAddressToString} ) -join ";"
}
catch {"Invalid HostName" - $server}
}
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname = $server
IP = $IP
}
$array += $obj
}
$array | Export-Csv -NoTypeInformation $env:userprofile\Desktop\ping_IP_host\results.csv
Output:
"IP","Hostname"
"216.58.206.68;2a00:1450:4002:803::2004","www.google.com"
"Invalid Host","jupiter"
"Invalid host","microsoft.com"
Select IPv4 address only
$array=#()
$computer=Get-Content -Path $env:userprofile\computers.txt
ForEach ($server in $computer) {
if (Test-Connection $server -Quiet -count 1) {
try {
$IP = [System.net.dns]::GetHostEntry($server).AddressList | Where-Object {$_.AddressFamily -eq 'InterNetwork'} | ForEach-Object {$_.IPAddressToString}
}
catch {"Invalid HostName" - $server}
}
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname = $server
IP = $IP
}
$array += $obj
}
$array | Export-Csv -NoTypeInformation $env:userprofile\Desktop\ping_IP_host\results.csv
Output:
"IP","Hostname"
"216.58.206.68","www.google.com"
"Invalid Host","jupiter"
"Invalid host","microsoft.com"

Duplicated results in Powershell

I have put together a script from various sources, but cannot understand why i am getting duplicated entries in my results..
eg..
I need to check the scheduled tasks on remote servers, and verify which ones didnt complete sucesfully, and then investigate those.
I have a schedulers.csv file, which has two comlumns IP, and Name.
I downloaded the script Get-ScheduledTask.ps1 from https://gallery.technet.microsoft.com/scriptcenter/Get-Scheduled-tasks-from-3a377294
Works great and does what i needed.
I then wanted to from a list retrieve the servers names, run the above script as a parameter, then get back the scheduled tasks in a csv file.
NextRunTime Author Trigger State UserId ComputerName Name LastRunTime LastTaskResult Description NumberOfMissedRuns Enabled Path
The headers for the above script give me Name and LastTaskResult, which is what I wanted to query further.
The LastTaskResult should be 0 if it completed sucesfully, otherwise i would investigate further.
The code i have so far is :
$servers = Import-Csv "C:\test\schedulers.csv"
foreach($server in $servers){
$ServerName = $server.Name
$ServerAddress = $server.IP
Write-Host $ServerName : $ServerAddress
$importfile = Get-ScheduledTask.ps1 -ComputerName $ServerName
|Export-Csv -Path c:\test\scheds.csv -NoTypeInformation
$Lines = Import-Csv "C:\test\scheds.csv"
ForEach($line in $lines){
$lines | %{
$TaskName = $_.name
$taskresult = $_.LastTaskResult
if ($_.LastTaskResult -ne "0")
{
Write-Host $line.LastTaskResult : $_.name : $_.Path
}else{
}
}
}
}
There should be 3 results that show, that have a value of 1 in LastTaskResult, but i get about 38 which is the total amount of tasks on the two servers that i am testing on.
the 3 entries are there also as well, plus all the rest..
please can anyone see where i have gone wrong.. Many Thanks
not tested because i don't have your Get-ScheduledTask.ps1, but here's what i might change
$servers = Import-Csv "C:\test\schedulers.csv"
foreach ($server in $servers) {
$ServerName = $server.Name
$ServerAddress = $server.IP
Write-Host $ServerName : $ServerAddress
$importfile = Get-ScheduledTask.ps1 -ComputerName $ServerName
$importfile | Export-Csv -Path c:\test\scheds.csv -NoTypeInformation
foreach ($line in $importfile) {
if ($line.LastTaskResult -ne '0') {
Write-Host $line.LastTaskResult : $line.Name : $line.Path
}
}
}

Powershell Export to CSV from ForEach Loop

I'm new to Powershell but I've given it my best go.
I'm trying to create a script to copy a file to the All Users Desktop of all the XP machines in an Array. The script basically says "If the machine is pingable, copy the file, if not, don't." I then want to export this information into a CSV file for further analysis.
I've set it all but no matter what I do, it will only export the last PC that it ran though. It seems to run through all the PC's (tested with outputting to a txt file) but it will not log all the machines to a CSV. Can anyone give any advise?
$ArrComputers = "PC1", "PC2", "PC3"
foreach ($Computer in $ArrComputers) {
$Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet
$Output = #()
#Is the machine reachable?
if($Reachable)
{
#If Yes, copy file
Copy-Item -Path "\\servername\filelocation" -Destination "\\$Computer\c$\Documents and Settings\All Users\Desktop\filename"
$details = "Copied"
}
else
{
#If not, don't copy the file
$details = "Not Copied"
}
#Store the information from this run into the array
$Output =New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv
Write-output "Script has finished. Please check output files."
The problem is this:
#Store the information from this run into the array
$Output =New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv
Each iteration of your foreach loop saves to $Output. Overwriting what was there previously, i.e., the previous iteration. Which means that only the very last iteration is saved to $Output and exported. Because you are running PowerShell v2, I would recommend saving the entire foreach loop into a variable and exporting that.
$Output = foreach ($Computer in $ArrComputers) {
New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
$Output | Export-Csv C:\GPoutput.csv
You would want to append the export-csv to add items to the csv file
Here is an example
foreach ($item in $ITGlueTest.data)
{
$item.attributes | export-csv C:\organization.csv -Append
}
Here you go. This uses PSCustomObject which enumerates data faster than New-Object. Also appends to the .csv file after each loop so no overwriting of the previous data.
foreach ($Computer in $ArrComputers) {
$Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet
#Is the machine reachable?
if($Reachable)
{
#If Yes, copy file
Copy-Item -Path "\\servername\filelocation" -Destination "\\$Computer\c$\Documents and Settings\All Users\Desktop\filename"
$details = "Copied"
}
else
{
#If not, don't copy the file
$details = "Not Copied"
}
#Store the information from this run into the array
[PSCustomObject]#{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Export-Csv C:\yourcsv.csv -notype -Append
}

Powershell - Get server name and IP from text list

I am using the following suggestion provided in this link:
Experts-Exchange
I am trying to take a server (host name) list and save the host name and IP address in a .csv file.
Using the following Powershell code, I do see the host name but the same IP address, for every server, in the results pane.
$servers = get-content "C:\TEMP\servers.txt"
$serversAndIps = "C:\TEMP\List_of_servers_with_ips.csv"
$results =#()
foreach ($server in $servers) {
$results =#()
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
$result.servername = $server
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips
When I open the .csv file, I get this:
"ServerName","ipaddress"
"Server_name_1","System.Net.IPAddress[]"
If I run this PowerShell script, I can get the host name and the correct IP address in the results pane. I just need to know how to transfer the results to a .csv file.
$servers = get-content "C:\TEMP\servers.txt"
foreach ($server in $servers) {
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
}
Any suggestions?
Looks like some simple typos at work.
$result was being reset inside the in the loop
$addresses inside the loop wasn't assigned.
$result.ipaddress was not assigned to $a.IPAddressToString for the output object.
Try this:
$servers = get-content "X:\servers.txt"
$serversAndIps ="X:\test.csv"
$results = #()
foreach ($server in $servers)
{
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses)
{
"{0},{1}" -f $server, $a.IPAddressToString
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
}
$result.servername = $server
$result.ipaddress = $a.IPAddressToString
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips