powershellloggingoutputdhcp

I need help printing the output of DHCP Powershell commands for logging


I am admittedly very new and not knowledgeable in PowerShell scripting. I am attempting to write a code that will parse through DHCP Scopes/Reservations looking for BAD ADDRESS reservations and then delete those. Through research I have been able to right up this code:

Get-DhcpServerv4Scope -ComputerName $DHCPServer | Get-DhcpServerv4Reservation -ComputerName $DHCPServer | Where-Object -FilterScript {$_.Name -eq 'BAD_ADDRESS'} #| Remove-DhcpServerv4Reservation

With the Remove-DhcpServerv4Reservation commented it out while I test.

Which brings me to where I am stuck. For testing and for logging I want to print the output of this code to a text document so I can be sure that it is picking up the BAD ADDRESS reservation like it is supposed to. To break things down further I want it to print the scope that the BAD ADDRESS was found and confirmation that the reservation was deleted. I know this can be complicated depending on how I want to format it to print out but honestly I just have no idea where to start with this.

Any help or guidance will be greatly appreciated.


Solution

  • For outputting the results to a text file, simply passing it to Out-File will basically do the job, but depending on what is being outputted, how many columns are included, how wide they are etc your results can vary.

    I'd go with :

    Get-DhcpServerv4Scope | Format-Table -AutoSize | Out-File myfile.txt -Width 500

    which should ensure the entire thing is outputted as needed.

    -AutoSize ensures that it doesn't trim off the ends of long columns, while -Width allows the outputted lines to be longer than the default, which I think is essentually tied to the standard width of a shell window.

    Another option if you'd like your output to both display on screen AND be saved to text file would be to use Tee-Object. For example

    Get-DhcpServerv4Scope | Format-Table -AutoSize | Out-String -Width 500 | Tee-Object myfile.txt

    which results in the formatted list being displayed on screen, and simultaneously written out to text file.

    With each of these, the source of your output can either be direct or from a variable you've pre-prepared. So for instance if you wanted to pass that output to the Remove command, and then spit it out to a text file then you could do something like this.

    $badReservations = Get-DhcpServerv4Scope -ComputerName $DHCPServer | Get-DhcpServerv4Reservation -ComputerName $DHCPServer | Where-Object -FilterScript {$_.Name -eq 'BAD_ADDRESS'}
    $badReservations | Remove-DhcpServerv4Reservation
    $badReservations | Format-Table -AutoSize | Out-File myfile.txt -Width 500
    

    So basically use that same list twice.