Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Need help reporting errors in a column on a CSV file

$
0
0

Running a script that queries servers for Network info.

Currently the script suppresses errors. I would like to report the errors and include them in the CSV file.

The end goal is a csv like this:

CN            IP Address    Subnet Mask      Error

Server1     10.10.10.2    255.255.255.0
Server2                                                      Access Denied
Server3     10.10.15.5    255.255.255.0
Server4                                                      RPC Server is unavailable 

 

My first attempt was to add a Write-Warning but that didn't work out so well. I need to add another object for the Error column but the output of the Write-Warning "Error occurred: $_" gave me 5 columns of info (IsFilter, StartPosition, File, Attributes, Module)

 

Thank you for your help.  Much appreciated.

 

Script:

 

[cmdletbinding()]

param (

 [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]

    [string[]]$ComputerName = $env:computername

)            

 

begin {}

process {

 foreach ($Computer in $ComputerName) {

  if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {

Try

{

$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer -ErrorAction Stop | ? {$_.IPEnabled} 

}

Catch {      

Write-Warning "Error occurred: $_"

}

{

continue

}

foreach ($Network in $Networks) {

    $IPAddress  = $Network.IpAddress[0]

    $SubnetMask  = $Network.IPSubnet[0]

    $DefaultGateway = $Network.DefaultIPGateway

    $DNSServers  = $Network.DNSServerSearchOrder

    $IsDHCPEnabled = $false

    If($network.DHCPEnabled) {

     $IsDHCPEnabled = $true

    }

    $MACAddress  = $Network.MACAddress

    $OutputObj  = New-Object -Type PSObject

    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()

    $OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress

    $OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask

$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value ($DefaultGateway -join ",")

    $OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled

    $OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value ($DNSServers -join ",")

    $OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress -Value $MACAddress

    $OutputObj

   }

  }

 }

}            

 

end {}


Viewing all articles
Browse latest Browse all 6937

Trending Articles