powershell - 尝试使用split方法将数字“50”与返回值“Free:50”隔离开来

时间:2014-11-29 18:22:10

标签: powershell dhcp

我希望我的问题不会因为违反某些规则而惹恼操作......当然不是我的意图。

我在Windows Server 2012 r2中安装了DHCP角色。之后,我使用Powershell设置了一个范围:

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

最终,我想做的是创建一个脚本,要求用户插入一个属于范围范围的IP地址,通过将其与 Get-DhcpServerv4FreeIPAddress <返回的ip进行比较来检查其可用性。 / em> cmdlet。

为了实现这一点,我首先需要知道范围内的免费ip的总数(为了简化事情,我将保留所有可用范围内的ip)并在某个地方,将该数字传递给Get-DhcpServerv4FreeIPAddress cmdlet的-NumAddress参数,因此我可以将用户选择的ip与返回的可用ip列表中的相应IP匹配。

所以,如果我写:

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

它返回:

Free : 50

...这就是我想要的......但是当我尝试拆分 Free:50 以便提取并存储数字'50'时,我的头痛就开始了。我所做的是存储管道的结果 Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 | Select-Object Free |格式化列表变成一个变量,并尝试使用 split 作为方法或运算符,最终将'50'从'Free:50'中取出,但到目前为止已证明不可能

例如,写作:

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

$a.Split(" : ")

返回:

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

而不是:

Free

50

Pd积。我有一个来自其他人的替代脚本,但它有一个稍微不同的方法,我总是倾向于让我的方法工作(即使用 split )。

任何帮助将不胜感激。提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试此操作以获得所需的值:

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

当您想要处理输出时,请不要使用Format-List

答案 1 :(得分:0)

您可以使用命令上的点表示法简单地访问该属性:

(Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0).Free

您还可以将结果存储在变量中,并使用点符号来获取存储结果的属性:

$a=Get-DhcpServerv4ScopeStatistics -ScopeId 10.0.0.0 
$a.Free

当管道中有多个对象时,点符号在版本3之前的Powershell上不起作用,在这种情况下,您需要使用manojlds的-Expand解决方案。