Unable to export the data to CSV or Excel - powershell

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 ....

Related

Stuck on where to add export-csv function

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

assign IP from text file

I have a scenario where I have below details in log.ini file.
Hostname : DLC1MQF
IP Address : 10.210.208.102
Temporary IP : 10.212.215.91
Subnet Mask : 255.255.248.0
Gateway : 10.212.208.1
What I am really looking here is I want check Default gateway is pinging or not. if not pinging I need to capture the IP,Subnet and Gateway from log.ini and assign that to my NIC.
Currently I am able to write a script like below and the problem is I am getting an error message that else is not a recognised command here.
$imagelog = Get-Content C:\Windows\ImageLog.ini
foreach ($line in $imagelog) {
if ($line -like "*Gateway*") {
$line | out-file -FilePath "C:\Windows\Gateway.txt"
}
}
$gatewayIP = get-content c:\windows\Gateway.txt
$GIP = $gatewayIp -replace '.*:.'.Trim()
if ( Test-Connection -ComputerName $Gip -Count 1 -ErrorAction SilentlyContinue ) {
Write-Host $GIP `t $GIP `t Ping Success -ForegroundColor Green
}
else{
$details = get-content c:\windows\imagelog.ini
foreach ($line in $details) {
if ($line -like "*IP Address*") {
$line | out-file -FilePath "C:\Windows\IP Address.txt"
}
#}
$IP = get-content c:\windows\IP Address.txt
$systemip = $Ip -replace '.*:.'.Trim()
foreach ($line in $details) {
if ($line -like "*Subnet Mask*") {
$line | out-file -FilePath "C:\Windows\subnet.txt"
}
}
$subnet = get-content c:\windows\subnet.txt
$subnetip = $subnet -replace '.*:.'.Trim()
netsh interface ip set address "Local Area Connection" static $systemip $subnetip $GIP
foreach ($line in $details) {
if (Hostname.StartsWith("LCG")) {
Set-DNSClientServerAddress –Local Area Connection –ServerAddresses (“10.0.6.65”,”10.0.25.65”,"10.0.0.1")
}
elseif (Hostname.StartsWith("ENG")) {
Set-DNSClientServerAddress –Local Area Connection –ServerAddresses (“10.80.38.33”,”10.0.25.65”,"10.0.0.1")
}
}
}
}
Any help is much appreciated.
You can wrap the test-connection in a try/catch block
Try{
test-connection $IP -ErrorAction Stop | out-null
write-output "working"
...do working stuff...
}Catch{
...do failed stuff...
write-output "failed"
}

Powershell: Trying to locate file in multiple drives from list of servers

I'm trying (and failing) to:
Connect to the server by iterating through a list.
Confirm location where file exists (1 of 3 locations).
Replace a string in that file.
I've tried to do this multiple ways. There are two that I have which do part of what I want.
Can someone please help me understand if there's something I'm doing inefficiently or how to put all this together?
This one can loop through the servers and find the file
$ErrorActionPreference = 'SilentlyContinue'
$nope=$null
$servers= Get-Content C:\Servers.txt
foreach ($server in $servers)
{
If (Test-Connection -ComputerName $server -Quiet)
{Invoke-Command -ComputerName $server -ScriptBlock {$file=(Get-Childitem -Path C:\DiskSpace.ps1, D:\DiskSpace.ps1, Y:\DiskSpace.ps1); Write-Host "Found $file on $env:computername."}}
Else {
Write-Host ">> Could not connect to $server."; $nope += $server}
}
Write-Host $nope
...and this one can at least find a local file
$valid=#('')
$paths = #("C:\Users\user_name\Desktop\DiskSpace.ps1","C:\DiskSpace.ps1","D:\DiskSpace.ps1","Y:\DiskSpace.ps1")
Foreach ($path in $paths)
{
if (Test-Path $path)
{$valid += $path}
}
write-host $valid
Here's how I intend to to replace the string:
$ErrorActionPreference = 'SilentlyContinue'
$find=(Get-Childitem -Path C:\, D:\, Y:\ -include DiskSpace.ps1 -Recurse)
Write-Host $find
$ErrorActionPreference = 'Stop'
try {
(Get-Content $find).replace('bad_email#domain.com', 'good_email#domain.com') | Set-Content $find
}
catch {
}
Get-Content $find
You had all the pieces already. Simply loop over your Get-Content command for each file in the Invoke-Command.
$ErrorActionPreference = 'SilentlyContinue'
$servers = Get-Content C:\Servers.txt
$files = #('C:\DiskSpace.ps1', 'D:\DiskSpace.ps1', 'Y:\DiskSpace.ps1')
$report = foreach ($server in $servers) {
if (Test-Connection -ComputerName $server -Quiet) {
$response = Invoke-Command -ComputerName $server -ScriptBlock {
Get-Childitem -Path $using:files | ForEach-Object {
(Get-Content $_).replace('bad_email#domain.com', 'good_email#domain.com') | Set-Content $_
[PSCustomObject]#{
Name = $env:COMPUTERNAME
Message = "$($_.fullname) updated."
}
}
}
if ($response -eq $null) {
[PSCustomObject]#{
Name = $env:COMPUTERNAME
Message = "No files found"
}
} else {
$response
}
} else {
[PSCustomObject]#{
Name = $env:COMPUTERNAME
Message = "Unreachable"
}
}
}
$report

Powershell get IPs from hosts programmatically

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

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