Answered by:
Get DNS server list with CSV report generation not exhaustif

Question
-
Hello,
I have this ps1 script for retrieving DNS servers on local or remote computers, it works fine, but when i send the result to CSV file, I only have information on reachable machines and nothing on the others !
I want to get also information related to machine not online, or to related rpc server not available on my CSV export, in the present state it's not the case :
Could you give me some help on how to proceed ?
Many thanks
Here is my code :
[cmdletbinding()] param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername.ToUpper() ) begin {} process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $CompStatus = Test-Connection -ComputerName $Computer -Count 1 -ErrorAction 0 if($CompStatus.StatusCode -eq 0) { $ComputterStatus = "Online" Write-Verbose "$Computer Computrer is online" try { $Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration ` -Filter IPEnabled=TRUE ` -ComputerName $Computer ` -ErrorAction Stop } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" continue } foreach($Network in $Networks) { $DNSServers = $Network.DNSServerSearchOrder $NetworkName = $Network.Description If(!$DNSServers) { $DNSCount = "Notset" $PrimaryDNSServer = "Notset" $SecondaryDNSServer = "Notset" $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" } elseif($DNSServers.count -eq 1) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = "Notset" $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" } elseif($DNSServers.count -eq 2) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" } elseif($DNSServers.count -eq 3) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = $DNSServers[2] $FouthdDNSServer = "Notset" } else { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = $DNSServers[2] $FouthdDNSServer = $DNSServers[3] } If($network.DHCPEnabled) { $IsDHCPEnabled = $network.DHCPEnabled } $OutputObj = New-Object -Type PSObject $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper() $OutputObj | Add-Member -MemberType NoteProperty -Name CompState -Value $ComputterStatus $OutputObj | Add-Member -MemberType NoteProperty -Name DNSCount -Value $DNSCount $OutputObj | Add-Member -MemberType NoteProperty -Name PrimaryDNSServers -Value $PrimaryDNSServer $OutputObj | Add-Member -MemberType NoteProperty -Name SecondaryDNSServers -Value $SecondaryDNSServer $OutputObj | Add-Member -MemberType NoteProperty -Name ThirdDNSServer -Value $ThirdDNSServer $OutputObj | Add-Member -MemberType NoteProperty -Name FouthdDNSServer -Value $FouthdDNSServer $OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled $OutputObj | Add-Member -MemberType NoteProperty -Name NetworkName -Value $NetworkName $OutputObj } } else { Write-Verbose "$Computer not reachable" } } } end {}
- Edited by Labark Thursday, April 5, 2018 7:53 AM
Wednesday, April 4, 2018 2:31 PM
Answers
-
This sounds good and works fine for me now. Many thanks for your time, your help, and your code reviews !
Really appreciated.
Function Get-DNSServers{ param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet -ea stop) { Write-Verbose "$Computer : ping successful" $results.CompState = 'Online' try { Write-Verbose "$Computer : Resquesting WMI..." [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $count = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName #$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index $results } } catch { Write-Verbose "Failed to Query wmi on $Computer. Error details: $($error[0].Exception.Message)" $results.Exception = $($error[0].Exception.Message) $results } } else { Write-Verbose "Ping Failed on $Computer" $results.Exception = "Test Connection Failed" $results } } $results } }
Thursday, April 12, 2018 8:30 AM
All replies
-
Could you please edit your post and format the code as code, as it is almost unreadable this way. Thanks.
Best regards,
(79,108,97,102|%{[char]$_})-join''
Wednesday, April 4, 2018 2:54 PM -
Post code using the code posting tool provided on the edit bar.
To add records from unresponsive systems you must generate a custom object with the information and blank fields and send to the output stream.
\_(ツ)_/
Wednesday, April 4, 2018 3:37 PM -
This is what your code needs to look like. I fixed some obvious errors but there are still a few logic errors that you will have to fix.
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { Write-Verbose "$_.ToUpper() Computrer is online" try { $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" } foreach($Network in $Networks) { $DNSServers = $Network.DNSServerSearchOrder $NetworkName = $Network.Description If(!$DNSServers) { $DNSCount = "Notset" $PrimaryDNSServer = "Notset" $SecondaryDNSServer = "Notset" $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" }elseif($DNSServers.count -eq 1) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = "Notset" $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" }elseif($DNSServers.count -eq 2) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = "Notset" $FouthdDNSServer = "Notset" }elseif($DNSServers.count -eq 3) { $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = $DNSServers[2] $FouthdDNSServer = "Notset" }else{ $DNSCount = $DNSServers.count $PrimaryDNSServer = $DNSServers[0] $SecondaryDNSServer = $DNSServers[1] $ThirdDNSServer = $DNSServers[2] $FouthdDNSServer = $DNSServers[3] } If($network.DHCPEnabled) { $IsDHCPEnabled = $network.DHCPEnabled } [pscustomobject]@{ ComputerName = $Computer.ToUpper() CompState = 'Online' DNSCount = $DNSCount PrimaryDNSServers = $PrimaryDNSServer SecondaryDNSServers = $SecondaryDNSServer ThirdDNSServer = $ThirdDNSServer FouthdDNSServer = $FouthdDNSServer IsDHCPEnabled = $IsDHCPEnabled NetworkName = $NetworkName } }else{ Write-Verbose "$Computer not reachable" [pscustomobject]@{ ComputerName = $Computer.ToUpper() CompState = 'Offline' DNSCount = $null PrimaryDNSServers = $null SecondaryDNSServers = $null ThirdDNSServer = $null FouthdDNSServer = $null IsDHCPEnabled = $null NetworkName = $null } } } } }
Notice that the code is readable and does not use old PS1 methods. PS1 is no longer supported although most PS1 scripts will run in later versions. PS3 and later syntax and extensions make code easier to write and read.
\_(ツ)_/
- Edited by jrv Wednesday, April 4, 2018 4:03 PM
Wednesday, April 4, 2018 3:55 PM -
If this test ("if($CompStatus.StatusCode -eq 0) {") fails, you only "Write-Verbose". So you get nothing for unreachable machines.
If this fails ("$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration"), your "catch" only does a Write-Verbose. So you get nothing in this case, too.
You'll have to add a new object in those two cases to have a data set for all machines.
This is a good case for making the object creation you do for "good" machines into a parameterized subroutine.
--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)
Wednesday, April 4, 2018 3:55 PM -
I will also warn you that what you have written does not produce a sensible output and creates many incorrect bits of data. You need to step back and learn about networking and how the adapters on a multi-homed machine work. The code written will not work on a system with more than one adapter.
\_(ツ)_/
Wednesday, April 4, 2018 3:58 PM -
If this test ("if($CompStatus.StatusCode -eq 0) {") fails, you only "Write-Verbose". So you get nothing for unreachable machines.
If this fails ("$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration"), your "catch" only does a Write-Verbose. So you get nothing in this case, too.
You'll have to add a new object in those two cases to have a data set for all machines.
This is a good case for making the object creation you do for "good" machines into a parameterized subroutine.
--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)
That is actually the hardest and least maintainable method although it can work.
The best thing is to refactor the code t create the output object at the beginning of the loop and assign the values as accessed then always outpu the object at the end of the loop.
\_(ツ)_/
Wednesday, April 4, 2018 4:07 PM -
Here is an example of how to set up a consistent object once and use it for all conditions. The object is initialized to the defaults for a failed connection and overwritten for each successful item retrieved.
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' DNSCount = $null PrimaryDNSServers = $null SecondaryDNSServers = $null ThirdDNSServer = $null FouthdDNSServer = $null IsDHCPEnabled = $null NetworkName = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' # other code to fill in $results } # always output results at the end of every loop $results } }
\_(ツ)_/
- Edited by jrv Wednesday, April 4, 2018 4:12 PM
- Proposed as answer by Albert LingMicrosoft contingent staff Thursday, April 5, 2018 1:32 AM
Wednesday, April 4, 2018 4:12 PM -
Hi, thanks a lot for your help ! Really appreciate it.
Sorry for the error related to the code during posting this topic. I will be careful next time.
I'll test that asap and get back to you. As i'am new ps1 user, i know that it's very perfectible and will not work for more than network card, it'll the the next step for improvement.
Regards
Wednesday, April 4, 2018 4:27 PM -
Now with refactoring, we can start to fill in each step and even easily add some information.
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null PrimaryDNSServers = "Notset" SecondaryDNSServers = "Notset" ThirdDNSServer = "Notset" FouthdDNSServer = "Notset" IsDHCPEnabled = "Notset" NetworkName = "Notset" Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count # other code to collect data and assign to results } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } } # always output results at the end of every loop $results } }
Note how easy it is to add the exception to the output on a pre computer basis.
Of course the adapter components should really be generating separate objects and not just simple DNS assignment.
"NotSet should just be null. If you want to display that then we would do it in an external formatter.
\_(ツ)_/
- Proposed as answer by Albert LingMicrosoft contingent staff Thursday, April 5, 2018 1:32 AM
Wednesday, April 4, 2018 4:28 PM -
Hi, thanks a lot for your help ! Really appreciate it.
Sorry for the error related to the code during posting this topic. I will be careful next time.
I'll test that asap and get back to you. As i'am new ps1 user, i know that it's very perfectible and will not work for more than network card, it'll the the next step for improvement.
Regards
You still need to fix your original post. Post thecode correctly.
Code standards for PowerShell: https://github.com/PoshCode/PowerShellPracticeAndStyle
For anyone who hasn't read a good article or book on code style and formatting the above link is a good place to start.
\_(ツ)_/
- Proposed as answer by Albert LingMicrosoft contingent staff Thursday, April 5, 2018 1:32 AM
Wednesday, April 4, 2018 4:32 PM -
Hi Jrv,
I tried to apply your method, it's partially working, some items are correctly filled but the related DNS fields are still empty, whereas when i check in the script i have the DNS IP adresses (in my example 2 DNS). The aim is to get a CSV report at the end.
Could you have a look please in this code ?
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null DNSCount = "Notset" PrimaryDNSServer = "Notset" SecondaryDNSServer = "Notset" ThirdDNSServer = "Notset" FourthdDNSServer = "Notset" IsDHCPEnabled = "Notset" NetworkName = "Notset" Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count # other code to collect data and assign to results : foreach($adapter in $adapters) { $DNSServers = $adapter.DNSServerSearchOrder $NetworkName = $adapter.Description If(!$DNSServers) { $results.DNSCount = "Notset" $results.PrimaryDNSServer = "Notset" $results.SecondaryDNSServer = "Notset" $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 1) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = "Notset" $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 2) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 3) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = $DNSServers[2] $results.FourthdDNSServer = "Notset" }else{ $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = $DNSServers[2] $results.FourthdDNSServer = $DNSServers[3] } } } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } # always output results at the end of every loop $results } } }
- Edited by Labark Friday, April 6, 2018 3:03 PM
Friday, April 6, 2018 2:59 PM -
OK Guys sorry GOT IT :) it was juste the variable names that differs, i corrected and now it's OK for that part.
Next step is for me to get a CSV output for reporting.
The code bellow is better now and is working fine to me.
Example :
ComputerName : TEST122736
CompState : Online
AdapterCount : 1
DNSCount : 2
PrimaryDNSServer : 10.1XX.1XX.1
SecondaryDNSServer : 10.1XX.1XX.2
ThirdDNSServer : Notset
FourthdDNSServer : Notset
IsDHCPEnabled : False
NetworkName : Intel(R) Ethernet Connection I219-LM
Exception :
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null DNSCount = "Notset" PrimaryDNSServer = "Notset" SecondaryDNSServer = "Notset" ThirdDNSServer = "Notset" FourthdDNSServer = "Notset" IsDHCPEnabled = "Notset" NetworkName = "Notset" Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count # other code to collect data and assign to results : foreach($adapter in $adapters) { $DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.NetworkName = $adapter.Description If(!$DNSServers) { $results.DNSCount = "Notset" $results.PrimaryDNSServer = "Notset" $results.SecondaryDNSServer = "Notset" $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 1) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = "Notset" $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 2) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = "Notset" $results.FourthdDNSServer = "Notset" }elseif($DNSServers.count -eq 3) { $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = $DNSServers[2] $results.FourthdDNSServer = "Notset" }else{ $results.DNSCount = $DNSServers.count $results.PrimaryDNSServer = $DNSServers[0] $results.SecondaryDNSServer = $DNSServers[1] $results.ThirdDNSServer = $DNSServers[2] $results.FourthdDNSServer = $DNSServers[3] } <# If($adapter.DHCPEnabled) { $results.IsDHCPEnabled = $adapter.DHCPEnabled } #> } } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } # always output results at the end of every loop $results } } }
Friday, April 6, 2018 3:21 PM -
You didn't use my code. You just turned it back into your old method and your method won't work.
Start by defining what the output should be as a table.
You are trying to mix apples and oranges and the approach is what I call the "bludgeon" approach to coding.
Each adapter can have completely different DNS settings. You are just overwriting everything.
Either produce the output per adapter or skip DNS all together. Which method depends on what the use is for the output.
\_(ツ)_/
Friday, April 6, 2018 3:35 PM -
This will give you the correct results per adapter with the correct DNS servers for that adapter
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null Description = $null DNSServers = $null IsDHCPEnabled = $null NetworkName = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.Description = $adapter.Description $results.DNSServers = $adapter.DNSServerSearchOrder $results } } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } } } }
\_(ツ)_/
Friday, April 6, 2018 3:45 PM -
This is all you need to do to load the DNS servers:
$count = $adapter.DNSServerSearchOrder.Count
The "NotSet" is already assigned at the beginning of each loop.
if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]}
\_(ツ)_/
- Edited by jrv Friday, April 6, 2018 4:04 PM
Friday, April 6, 2018 4:03 PM -
Hi,
Thanks a lot for your feedback !
I try to get it well done. I have good results now,
With this command i can export to csv now :
PS C:\Temp\...\Get-DNSServers> .\Get-DNSServers.ps1 -ComputerName "hostname"| Export-Csv C:\Temp\...\Get-DNSServers\DNSresult.csv
param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index $results } } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } } } }
Monday, April 9, 2018 10:27 AM -
This can be easily done like this:
$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID
Also your method will always get the id of the local machine.
\_(ツ)_/
Monday, April 9, 2018 10:32 AM -
Also your "$count" variable is never set.
Change this:
$results.DNSCount =$count = $adapter.DNSServerSearchOrder.Count
\_(ツ)_/
- Edited by jrv Monday, April 9, 2018 10:34 AM
Monday, April 9, 2018 10:33 AM -
Hi,
Ok, i tried your way for FriendlyName,
$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID
but it's not working on my side as i'am with Poweshell v2. (PSVersion= 2.0) Whereas on my laptop I'am on 5.1 version (PSVersion =5.1.14393.2125).
On my CSV output I have this output :
#TYPE System.Collections.Hashtable
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","14"
How can I proceed for having a good filled CSV file please ?
Thanks
Monday, April 9, 2018 1:22 PM -
You should not be using PowerShell V2 due to security issues. Pleas upgrade your system.
You export failure is because you have a mistake in your code somewhere.
\_(ツ)_/
Monday, April 9, 2018 2:20 PM -
If I run this:
function Get-SysConfig{ param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index $results } } catch { Write-Verbose "Failed to Query $Computer. Error details: $_" $results.Exception = $_ } } } } } Get-SysConfig ws702,sbs01 |export-Csv test.csv -notype Get-Content test.csv
This is my CSV:
"ComputerName","CompState","AdapterCount","NetworkName","DNSCount","DNS1","DNS2","DNS3","DNS4","IsDHCPEnabled","FriendlyName","ServiceName","Index","Exception" "ws702","Online","1","Intel(R) 82579LM Gigabit Network Connection","1","NotSet","NotSet","NotSet","NotSet","True","LAN","e1cexpress","7", "sbs01","Online","1","Broadcom NetXtreme Gigabit Ethernet","1","NotSet","NotSet","NotSet","NotSet","False","LAN","b57nd60a","7",
PowerShell 2 does not support custom objects.
\_(ツ)_/
Monday, April 9, 2018 2:24 PM -
Hi,
I confirm this way the CSV export is working well ! But I only have result concerning working machines, for thoses ones who I have an exception error (not online, on rpc not available, access denied) they are not part of the CSV file :(
Normally it's will have to.
Could you try with a non valid Hostname and try to test it on your side please ?
Regards
- Edited by Labark Monday, April 9, 2018 4:18 PM
Monday, April 9, 2018 4:06 PM -
$results needs to be at the end of the loop.
\_(ツ)_/
Monday, April 9, 2018 4:19 PM -
Hi,
OK, i tried but I really dont know how to proceed. Furthermore, I'am able to see the execption error when I execute this part of code (I replaced Write-Verbose by Write-Host because with Write-Verbose i cant see nothing thrown)
try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $count = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) #$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID *dont work with pshell 2 $results.Index = $adapter.Index $results } } catch { Write-Host "Failed to Query $Computer. Error details: $_" $results.Exception = $_ }
Result with invalide computer name :
Failed to Query test2000. Error details: Le serveur RPC n’est pas disponible. (Exception from HRESULT: 0x800706BA)
When I execute the function, with one valide machine and invalide one, i'am not able to retreive errors for invalide one :
PS C:\Windows\system32> Get-SysConfig -ComputerName TEST2000, VAIO
Working on TEST2000 ==> Here I have nothing !! Strange
Working on VAIO
VAIO is online
ComputerName : VAIO
CompState : Online
AdapterCount : 1
NetworkName : Atheros AR9285 Wireless Network Adapter
DNSCount : 2
DNS1 : 8.8.8.8
DNS2 : 8.8.4.4
DNS3 : NotSet
DNS4 : NotSet
IsDHCPEnabled : True
FriendlyName : Connexion réseau sans fil
ServiceName : athr
Index : 7
Exception :
PS C:\Windows\system32>
Please could you help ? Thanks a lot as i'am noob in PShell.
Monday, April 9, 2018 8:23 PM -
Please post the complete error message.
\_(ツ)_/
Monday, April 9, 2018 8:28 PM -
I can have several kind of errors like this ones :
Failed to Query test2000. Error details: Le serveur RPC n’est pas disponible. (Exception from HRESULT: 0x800706BA)
Access denied
Sometimes nothing
And my issue is that i only have successful results in the CSV, what i am seeking for is to have successful results in CSV file and also negative results for failed machines so i can report and manage them as i will know why the process failed.
Example of Output without CSV export :
ERBOSE: Working on 192.1688.xx.xx
VERBOSE: Failed to Query 1920.168.xx.xx Error details: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
VERBOSE: Working on 192.168.xx.xx
VERBOSE: Failed to Query 192.168.xx.xx. Error details: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
VERBOSE: Working on E2xxxxxBK
VERBOSE: Working on E2xxxxxMN
VERBOSE: Working on EBxxxxxTS
VERBOSE: Working on EBxxxxxTS
VERBOSE: Working on epxxxx01
VERBOSE: Failed to Query epxxxxx01 Error details: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
VERBOSE: Working on epxxxxxxxx002
VERBOSE: Failed to Query epxxxxxx002 Error details: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
VERBOSE: Working on epxxxxxxxx006
VERBOSE: Working on epxxxxxx007
VERBOSE: Failed to Query epxxxxxx007 Error details: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
VERBOSE: Working on EPxxxxxxxxxB
VERBOSE: Working on EPxxxxxxxxxBWhen succefful i have this that is gone correctly to CSV file :
VERBOSE: Working on euxxxxx507
ComputerName euxxxxx507
ServiceName q57xxxxa
Exception
CompState OnlineNetworkName HP Ethernet 1Gb xxxx
DNS3 NotSet
DNS1 xxx.xxx.xxx.3
IsDHCPEnabled False
Index 13
AdapterCount 1
DNSCount 2
DNS2 xxx.xxx.xxx.2
FriendlyName LAN
DNS4 NotSet
Tuesday, April 10, 2018 8:48 AM -
As I notes above. You have to output the results at the end of the outer loop and not the inner loop.
\_(ツ)_/
Tuesday, April 10, 2018 9:03 AM -
OK, I tried several time without success. I dont know how to do that. My all tests are not working.
Please advise. Kind regards.
Tuesday, April 10, 2018 9:42 AM -
What did you try???
\_(ツ)_/
Tuesday, April 10, 2018 9:47 AM -
I tried this :
Function Get-SysConfig{ param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Host "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet) { $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $count = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName #$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index $results } } catch { Write-Host "Failed to Query $Computer. Error details: $_" $results.Exception = $_ $results } } else { Write-Host "Failed to Query $Computer. Error details: $_" $results.Exception = $_ $results } } } }
Tuesday, April 10, 2018 2:21 PM -
No. Only one $results output at the end of the outer loop You are outputting all over the place.'
\_(ツ)_/
Tuesday, April 10, 2018 2:46 PM -
OK, this works almost, i can retreive data for offline computers, but no exception thrown by the gwmi command, like RPC not available or access denied, Do i have to add some traps in my catch ? Like that ? :
try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop } catch [System.UnauthorizedAccessException] { Write-Host -ForegroundColor DarkRed "Access Denied to $computer"; $results.Exception = $_ } catch [System.Management.ManagementException] { Write-Host -ForegroundColor DarkRed "Access Denied to $computer"; $results.Exception = $_ } catch [System.Exception] { if($_.Exception.GetType() -like "COMException") { Write-Host -ForegroundColor DarkRed "The RPC Server is Unavailable on $computer"; $results.Exception = $_ } }
Code :
Function Get-SysConfig{ param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Host "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet -ea stop) { Write-Host "$Computer : ping successful" $results.CompState = 'Online' try { [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $count = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName #$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index #$results } } catch { Write-Host "Failed to Query wmi on $Computer. Error details: $_Exception.Message" $results.Exception = $_ #$results } } else { Write-Host "Ping Failed on $Computer. Error details: $_Exception.Message" $results.Exception = $_ #$results } } $results } }
Tuesday, April 10, 2018 4:43 PM -
Some exceptions cannot be trapped.
\_(ツ)_/
Tuesday, April 10, 2018 4:46 PM -
This sounds good and works fine for me now. Many thanks for your time, your help, and your code reviews !
Really appreciated.
Function Get-DNSServers{ param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]] $ComputerName = $env:computername ) process { foreach($Computer in $ComputerName) { Write-Verbose "Working on $Computer" $results = [pscustomobject]@{ ComputerName = $Computer CompState = 'Offline' AdapterCount = $null NetworkName = $null DNSCount = $null DNS1 = "NotSet" DNS2 = "NotSet" DNS3 = "NotSet" DNS4 = "NotSet" #DNSServers = $null IsDHCPEnabled = $null FriendlyName = $null ServiceName = $null Index = $null Exception = $null } if(Test-Connection -ComputerName $Computer -Count 1 -Quiet -ea stop) { Write-Verbose "$Computer : ping successful" $results.CompState = 'Online' try { Write-Verbose "$Computer : Resquesting WMI..." [array]$adapters= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -ComputerName $Computer -ErrorAction Stop $results.AdapterCount = $adapters.Count foreach($adapter in $adapters){ $results.DNSCount = $count = $adapter.DNSServerSearchOrder.Count $results.NetworkName = $adapter.Description if($count -ge 1){$results.DNS1 = $adapter.DNSServerSearchOrder[0]} if($count -ge 2){$results.DNS2 = $adapter.DNSServerSearchOrder[1]} if($count -ge 3){$results.DNS3 = $adapter.DNSServerSearchOrder[2]} if($count -ge 4){$results.DNS4 = $adapter.DNSServerSearchOrder[3]} #$results.DNSServers = $adapter.DNSServerSearchOrder $results.IsDHCPEnabled = $adapter.DHCPEnabled $results.ServiceName = $adapter.ServiceName #$results.FriendlyName = $adapter.GetRelated('Win32_NetworkAdapter').NetConnectionID $results.FriendlyName = (Get-WmiObject Win32_NetworkAdapter -Filter "Netconnectionstatus=2" | Select-Object -ExpandProperty NetConnectionID) $results.Index = $adapter.Index $results } } catch { Write-Verbose "Failed to Query wmi on $Computer. Error details: $($error[0].Exception.Message)" $results.Exception = $($error[0].Exception.Message) $results } } else { Write-Verbose "Ping Failed on $Computer" $results.Exception = "Test Connection Failed" $results } } $results } }
Thursday, April 12, 2018 8:30 AM -
Your code is still wrong and won't return what you think.
\_(ツ)_/
Thursday, April 12, 2018 9:25 AM -
:( feel free to review it :)
Thanks again. It suits my needs so for the moment it's suffcient to me.
kind regards
Thursday, April 12, 2018 7:12 PM -
Hi,
I'm checking how the issue is going, was your issue resolved?
And if the replies as above are helpful, we would appreciate you to mark them as answers, and if you resolve it using your own solution, please share your experience and solution here. It will be greatly helpful to others who have the same question.
Appreciate for your feedback.
Best Regards,
AlbertPlease remember to mark the replies as an answers if they help.
If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.comFriday, April 13, 2018 7:49 AM -
Hello, yes to me its solved now, i get what i need in term of reporting.
Regards
Saturday, April 14, 2018 3:17 PM