80 lines
2.4 KiB
C#
80 lines
2.4 KiB
C#
namespace PS.IPAM.Cmdlets;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Management.Automation;
|
|
using System.Net;
|
|
using PS.IPAM;
|
|
using PS.IPAM.Helpers;
|
|
|
|
[Cmdlet(VerbsCommon.Get, "FirstFreeIP", DefaultParameterSetName = "ByID")]
|
|
public class GetFirstFreeIPCmdlet : PSCmdlet
|
|
{
|
|
[Parameter(
|
|
Mandatory = true,
|
|
ValueFromPipeline = true,
|
|
ValueFromPipelineByPropertyName = true,
|
|
Position = 0,
|
|
ParameterSetName = "ByCIDR")]
|
|
[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")]
|
|
[ValidateNotNullOrEmpty]
|
|
public int? Id { get; set; }
|
|
|
|
[Parameter(
|
|
Mandatory = false,
|
|
ValueFromPipeline = true,
|
|
ValueFromPipelineByPropertyName = true,
|
|
Position = 0,
|
|
ParameterSetName = "BySubnetObject")]
|
|
[ValidateNotNullOrEmpty]
|
|
public Subnetwork? SubnetObject { get; set; }
|
|
|
|
protected override void ProcessRecord()
|
|
{
|
|
try
|
|
{
|
|
int subnetId;
|
|
if (ParameterSetName == "ByCIDR")
|
|
{
|
|
var subnet = RequestHelper.InvokeRequest("GET", controllers.subnets, types.Subnetwork, null, null, new[] { "cidr", CIDR! })
|
|
.GetAwaiter().GetResult();
|
|
if (subnet == null)
|
|
{
|
|
throw new Exception("Cannot find subnet!");
|
|
}
|
|
var subnetObj = subnet as Subnetwork;
|
|
subnetId = subnetObj!.Id;
|
|
}
|
|
else if (ParameterSetName == "BySubnetObject")
|
|
{
|
|
subnetId = SubnetObject!.Id;
|
|
}
|
|
else
|
|
{
|
|
subnetId = Id!.Value;
|
|
}
|
|
|
|
var identifiers = new List<string> { subnetId.ToString(), "first_free" };
|
|
var result = RequestHelper.InvokeRequest("GET", controllers.subnets, null, null, null, identifiers.ToArray())
|
|
.GetAwaiter().GetResult();
|
|
|
|
if (result != null)
|
|
{
|
|
WriteObject(new { Ip = result.ToString() });
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
WriteError(new ErrorRecord(ex, "GetFirstFreeIPError", ErrorCategory.InvalidOperation, null));
|
|
}
|
|
}
|
|
}
|