87 lines
2.5 KiB
C#
87 lines
2.5 KiB
C#
namespace PS.IPAM.Cmdlets;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Management.Automation;
|
|
using PS.IPAM.Helpers;
|
|
|
|
/// <summary>
|
|
/// Retrieves subnet usage statistics from phpIPAM.
|
|
/// </summary>
|
|
[Cmdlet(VerbsCommon.Get, "SubnetUsage", DefaultParameterSetName = "ByID")]
|
|
public class GetSubnetUsageCmdlet : BaseCmdlet
|
|
{
|
|
[Parameter(
|
|
Mandatory = true,
|
|
ValueFromPipeline = true,
|
|
ValueFromPipelineByPropertyName = true,
|
|
Position = 0,
|
|
ParameterSetName = "ByCIDR",
|
|
HelpMessage = "The subnet in CIDR notation.")]
|
|
[ValidatePattern(@"^\d+\.\d+\.\d+\.\d+/\d{1,2}$")]
|
|
[ValidateNotNullOrEmpty]
|
|
public string? CIDR { get; set; }
|
|
|
|
[Parameter(
|
|
Mandatory = true,
|
|
ValueFromPipeline = true,
|
|
ValueFromPipelineByPropertyName = true,
|
|
Position = 0,
|
|
ParameterSetName = "ByID",
|
|
HelpMessage = "The subnet ID.")]
|
|
[ValidateNotNullOrEmpty]
|
|
public int? Id { get; set; }
|
|
|
|
[Parameter(
|
|
Mandatory = true,
|
|
ValueFromPipeline = true,
|
|
Position = 0,
|
|
ParameterSetName = "BySubnetObject",
|
|
HelpMessage = "The subnet object.")]
|
|
[ValidateNotNullOrEmpty]
|
|
public Subnetwork? SubnetObject { get; set; }
|
|
|
|
protected override void ProcessRecord()
|
|
{
|
|
try
|
|
{
|
|
var subnetId = GetSubnetId();
|
|
var identifiers = new List<string> { subnetId.ToString(), "usage" };
|
|
|
|
var result = RequestHelper.InvokeRequest(
|
|
"GET", ApiController.Subnets, null, null, null, identifiers.ToArray()
|
|
).GetAwaiter().GetResult();
|
|
|
|
WriteResult(result);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
WriteError(new ErrorRecord(ex, "GetSubnetUsageError", ErrorCategory.InvalidOperation, null));
|
|
}
|
|
}
|
|
|
|
private int GetSubnetId()
|
|
{
|
|
switch (ParameterSetName)
|
|
{
|
|
case "ByCIDR":
|
|
var subnet = RequestHelper.InvokeRequest(
|
|
"GET", ApiController.Subnets, ModelType.Subnetwork, null, null,
|
|
new[] { "cidr", CIDR! }
|
|
).GetAwaiter().GetResult() as Subnetwork;
|
|
|
|
if (subnet == null)
|
|
{
|
|
throw new ItemNotFoundException($"Subnet '{CIDR}' not found.");
|
|
}
|
|
return subnet.Id;
|
|
|
|
case "BySubnetObject":
|
|
return SubnetObject!.Id;
|
|
|
|
default:
|
|
return Id!.Value;
|
|
}
|
|
}
|
|
}
|