Search code examples
powershelldhcp

powershell - trying to use split method to isolate the number "50" from the returned value "Free : 50"


I hope my question doesn't annoy the ops for having broken some rule...certainly not my intention.

I have installed the DHCP role in Windows Server 2012 r2. After that, I have set up a scope using Powershell:

Add-DhcpServerv4Scope -name "ambito1" -StartRange 10.0.0.1 -EndRange 10.0.0.50  -SubnetMask 255.255.255.0

Ultimately, what I want to do is make a script which asks the user to insert an IP address falling within the scope's range which will be checked for availability by comparing it to those ip's returned by the Get-DhcpServerv4FreeIPAddress cmdlet.

In order to achieve this, I first need to know the total number of free ip's within the scope (to simplify things, I will keep all the ip's within the scope available) and somewhere down the line, pass that number to the -NumAddress parameter of the Get-DhcpServerv4FreeIPAddress cmdlet, so I can match the user's chosen ip with the corresponding one on the list of returned available ip's.

So if I write:

Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 | Select-Object Free | Format-List

it returns:

Free : 50

...which is what I want...but my headaches begin when I try to split Free : 50 in order to extract and store into a variable the number '50'. What I've done is store the result of the pipeline Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 | Select-Object Free | Format-List into a variable and try to use split as a method or an operator to ultimately get my '50' out of the 'Free : 50' but it has proven impossible so far.

For instance, writing:

$a=Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 | Select-Object Free | Format-List

$a.Split(" : ")

returns:

Microsoft.Powershell.Commands.Internal.Format.FormatStartData
Microsoft.Powershell.Commands.Internal.Format.GroupStartData
Microsoft.Powershell.Commands.Internal.Format.FormatEntryData
Microsoft.Powershell.Commands.Internal.Format.GroupEndData
Microsoft.Powershell.Commands.Internal.Format.FormatEndData

instead of:

Free

50

P.D. I have an alternative script from someone else which works but it has a slightly different approach and I'm hell bent on getting my approach to work (i.e. using split).

Any help would be appreciated. Thanks in advance.


Solution

  • Try this to get the value you want:

    Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 | Select-Object -Expand Free
    

    Don't use Format-List when you want to process the output.