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
Related
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 ....
Good day,
I have the following script below which i am using to get a specific value from a remote pc within the company network.
I am stuck on where I would add the export-csv function so that i can export all the data into a csv file.
any help would be appreciated.
$computers = Get-Content "c:\temp\Servers.txt"
$key = 'SOFTWARE\Fortinet\FortiClient\Sslvpn\Tunnels\RCL SSL VPN'
$valuename = 'Server'
$computers = Get-Content Servers.txt
foreach ($computer in $computers) {
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
$MachineName = $computer
$regkey = $reg.opensubkey($key)
Write-host $MachineName "," $regkey.getvalue($valuename) `r`n
}
You could use PsCustomObject and then add to it with each loop
$computers = Get-Content "c:\temp\Servers.txt"
$objarray = #()
$key = 'SOFTWARE\Fortinet\FortiClient\Sslvpn\Tunnels\RCL SSL VPN'
$valuename = 'Server'
$computers = Get-Content Servers.txt
foreach ($computer in $computers) {
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
$MachineName = $computer
$regkey = $reg.opensubkey($key)
Write-host $MachineName "," $regkey.getvalue($valuename) `r`n
$objArray += [PSCustomObject]#{
'MachineName' = $computer
'RegKey' = $RegKey
}
}
$objarray | export-csv c:\export.csv
Output objects inside the loop and pipe these through at the very end to the Export-Csv cmdlet like this:
$computers = Get-Content "c:\temp\Servers.txt"
$key = 'SOFTWARE\Fortinet\FortiClient\Sslvpn\Tunnels\RCL SSL VPN'
$valuename = 'Server'
$computers = Get-Content Servers.txt
$result = foreach ($computer in $computers) {
# do this in a Try{..] Catch {..} construct
try {
$regBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
$regkey = $regBase.OpenSubKey($key)
# output an object with the properties you want
[PsCustomObject]#{'MachineName' = $computer; RegistryValue = $regkey.GetValue($valuename) }
}
catch {
Write-Warning "Could not open registry on server '$computer'"
# output an object with the error
[PsCustomObject]#{'MachineName' = $computer; RegistryValue = "Error opening registry.." }
}
# for good measure, Close the opened registry
finally {
if ($regkey) { $regkey.Close() }
if ($regBase) { $regBase.Close() }
}
}
# output on screen
$result | Format-Table -AutoSize
#output to CSV file
$result | Export-Csv -Path 'c:\temp\ServerRegistryValues.csv' -NoTypeInformation
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"
I have a command t get the cluster details from list of VM'.
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
Get-Cluster (Get-VM $vm).ComputerName
}
and the output of the script shows only cluster details of VM as below
Name
----
dhypervcl001
dhypervcl001
dhypervcl001
Can anyone tell me , how I can get an out put in below format i.e servername and clustername
server1, dhypervcl001
server2, dhypervcl0011
server3, dhypervcl012
Using string.Format:
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
"{0},{1}" -f $vm, (Get-Cluster (Get-VM $vm).ComputerName)
}
Or PSCustomObject:
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
$Row = "" | Select Server,Cluster
$Row.Server = $VM
$Row.Cluster = (Get-Cluster (Get-VM $vm).ComputerName)
$Row
}
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