【问题标题】:Check if DHCP scope exists检查 DHCP 范围是否存在
【发布时间】:2016-01-25 11:50:29
【问题描述】:

我正在编写脚本以在 Powershell 4.0 中自动配置 Windows Server 2012。现在我设法创建了 DHCP 作用域、排除和保留,但我想在创建 DHCP 作用域之前对其进行测试/检查。

我的意思是,在运行我编写的函数(以创建新范围)之前,我首先要测试或检查 DHCP 范围是否已经存在。如果范围已经存在,我希望脚本跳过该功能。如果不是,我希望它运行函数来创建范围。 测试/检查的具体部分我不知道该怎么做。

【问题讨论】:

    标签: powershell windows-server-2012 dhcp powershell-4.0


    【解决方案1】:

    使用Get-DhcpServerv4Scope 列出现有范围,并通过Where-Object(别名?)过滤列表以获得您要验证的名称或ID:

    if (-not (Get-DhcpServerv4Scope | ? { $_.Name -eq 'foo' })) {
      Add-DhcpServerv4Scope ...
    }
    

    if (-not (Get-DhcpServerv4Scope | ? { $_.ScopeId -eq '192.168.23.0' })) {
      Add-DhcpServerv4Scope ...
    }
    

    您可以将检查包装在自定义函数中

    function Test-DhcpServerv4Scope {
      [CmdletBinding(DefaultParameterSetName='name')]
      Param(
        [Parameter(Mandatory=$true, ParameterSetName='name')]
        [string]$Name,
        [Parameter(Mandatory=$true, ParameterSetName='id')]
        [string]$ScopeId
      )
    
      $p = $MyInvocation.BoundParameters.Keys
    
      [bool](Get-DhcpServerv4Scope | Where-Object {
        $_.$p -eq $MyInvocation.BoundParameters[$p]
      })
    }
    

    并像这样使用它:

    if (-not (Test-DhcpServerv4Scope -Name 'foo')) {
      Add-DhcpServerv4Scope ...
    }
    

    或者像这样:

    if (-not (Test-DhcpServerv4Scope -ScopeId '192.168.23.0')) {
      Add-DhcpServerv4Scope ...
    }
    

    如果您正在处理 IPv6 范围,请将 *-DhcpServerv4Scope 替换为 *-DhcpServerv6Scope

    【讨论】:

    • 谢谢!我只需要弄清楚 .BoundParameters.Keys 代表什么,但我会自己查一下。我想可以从我将通过另一个 Cmdlet 获得的变量中获取 -name 和 -scopid 参数。只是为了让它更灵活一点,我不必对这些参数进行硬编码。
    【解决方案2】:

    如果您尝试远程检查,例如通过 CimSession,您可以得到这样的快速布尔答案:

    If((get-dhcpserverv4scope -CimSession $CimSession).ScopeId -contains "1.10.20.0" ) 
    {... Then do this}
    else { do this }
    

    【讨论】:

      猜你喜欢
      • 2018-05-12
      • 2012-05-08
      • 2023-04-03
      • 2017-07-13
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多