Search code examples
powershelltry-catchdhcp

How can i correctly output my try-catch into a txt file?


I'm working on a powershell script that would allow me to see if my DHCP servers are running well and what's their current state (how much address left, how much of them are used...).

So far, so good. I'm getting all the info i need but, the first test here is to check if the server is responding pretty much.

For this, i'm using try-catch and i'd like to output into a .txt all of the servers that are not responding. Problem : i'm only outputting the last server that did not respond, i'm not getting the previous one that did not respond aswell.

Tried | out-file | set-content and | add-content There's nothing that i've found searching seems to work.

$DHCPSRV=""
$myError=0
$myArray=@( Import-Csv .\CSV\DHCP_list.csv)
foreach ($element in $myArray) {

try {

Write-Output ""
$DHCPSRV=$element.FQDN
$Message = "Server DHCP: " + $DHCPSRV
Write-Output $Message
Write-Output ""
$srv=get-dhcpserverv4statistics -ComputerName $DHCPSRV 
$Message ="Server start time : "  + $srv.ServerStartTime 
Write-Output $Message
$Message ="Number of address : "  + $srv.TotalAddresses
Write-Output $Message
$Message ="Address used : "  + $srv.AddressesInUse
Write-Output $Message
$Message ="% remaining : "  + $srv.PercentageAvailable + " %"
Write-Output $Message     
Get-DhcpServerSetting -ComputerName $DHCPSRV
Write-Output ""

}
catch{

  Write-host "Server not responding "  $DHCPSRV -BackgroundColor red      -ForegroundColor White 
 $myerror=$error+1 
  $test =  $DHCPSRV   

   }    
}

 if ($myError -eq 0){
   Write-Output ""
 Write-host "All DHCP are working good"  -BackgroundColor green    -ForegroundColor black 

    }

$test | Set-Content '.\Output\dhcp_failed.txt'
 $test | Add-Content '.\Output\dhcp_failed.txt'
 Write-Output ""
Write-Output ""
 Write-Output "------------------------------------------------"
pause 

I'd like to output all of the server that failed the try-catch test in my txt!


Solution

  • solved by bluuf - Thank you !

    Just had to add the -append in my catch

    catch{
      Write-host "Server not responding "  $DHCPSRV -BackgroundColor red -ForegroundColor White 
     $myerror=$error+1 
     $DHCPSRV | out-file '.\path\file.txt' -append   
       }   
    

    also added clear-content '.\path\file.txt' at the beginning of the script so my file get cleared every time i launch it!