2016-09-18 26 views
0

我试图在报告中添加ping失败的服务器,但是异常不会将结果添加到datagridview ..我在哪里出错?在datagridview中没有为ping失败的服务器添加异常

function Test-Ping { 
    $Servers = Get-Content $textboxServerName.txt 
    $Set = @() 
    foreach ($Server in $Servers) { 
    try { 
     $Set += Test-Connection -ComputerName $Server -Count 1 | 
       Select -Property @{n='ServerName';e={$_.PSComputerName}}, 
           @{n='IPv4';e={$_.IPV4Address}}, 
           @{n='IPv6';e={$_.IPV6Address}}, 
           @{n='ProtocolAddress';e={$_.ProtocolAddress}} -ErrorAction Stop 
    } catch [System.Exception] { 
     $Set += @{n='ServerName';e={$_.PSComputerName}}, 
       @{n='IPv4';e={N/A}}, 
       @{n='IPv6';e={N/A}}, 
       @{n='ProtocolAddress';e={N/A}} 
    } 
    $table = ConvertTo-DataTable -InputObject $Set -FilterWMIProperties 
    Load-DataGridView -DataGridView $datagridview1 -Item $table 
    } 
} 

回答

0

你的代码有几个问题。

  • Get-Content $textboxServerName.txt可能无法按照您的想法工作。是否要将后缀.txt附加到值$textboxServerName?如果变量(字符串?)不具有该属性,则表达式将计算为$null,因此Get-Content将失败并产生ParameterBindingValidation异常。使用双引号,以防止:

    $Servers = Get-Content "$textboxServerName.txt" 
    

    还是$textboxServerName一个TextBox元素,并且希望该元素的文本值?在这种情况下,您拼错了房产名称(Text)。

    $Servers = Get-Content $textboxServerName.Text 
    
  • catch阻断​​$_保持异常对象,而不是Test-Connection结果(已经失败无论如何,因此不产生在所述第一位置的结果)。改为使用变量$Server

  • $Set追加哈希表列表的方式与Select-Object语句中的calculated properties列表不一样。您需要在那里创建一个自定义对象。

    New-Object -Type PSObject -Property @{ 
        'ServerName'  = $Server 
        'IPv4'   = 'N/A' 
        'IPv6'   = 'N/A' 
        'ProtocolAddress' = 'N/A' 
    } 
    
  • 追加到循环中的数组肯定会表现不佳。它通常最好只输出循环内的对象,收集在一个变量整个循环输出,并将其加载到网格视图循环结束后:

    $Set = foreach ($Server in $Servers) { 
        ... 
    } 
    $table = ConvertTo-DataTable -InputObject $Set -FilterWMIProperties 
    Load-DataGridView -DataGridView $datagridview1 -Item $table 
    
  • 如果要追加到网格视图随着循环的每次迭代你应该只是add new rows它:

    foreach ($Server in $Servers) { 
        try { 
        $o = Test-Connection -ComputerName $Server -Count 1 -ErrorAction Stop | 
         Select -Property @{n='ServerName';e={$_.PSComputerName}}, 
              @{n='IPv4';e={$_.IPV4Address}}, 
              @{n='IPv6';e={$_.IPV6Address}}, 
              @{n='ProtocolAddress';e={$_.ProtocolAddress}} 
        } catch [System.Exception] { 
        $o = New-Object -Type PSObject -Property @{ 
          'ServerName'  = $Server 
          'IPv4'   = 'N/A' 
          'IPv6'   = 'N/A' 
          'ProtocolAddress' = 'N/A' 
         } 
        } 
        $datagridview1.Rows.Add($o.ServerName, $o.IPv4, $o.IPv6, $o.ProtocolAddress) 
    } 
    
+0

安斯加尔感谢您在这一切帮助..我已经建立了基于给出建议的功能,得到了如下错误.. – Aamir

+0

ERROR :以“9”为参数调用“添加”的例外情况t(s):“当控件是数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。” – Aamir

+0

[google:// + + + +控件+ +数据绑定时,Rows +无法+以编程方式+添加+ + DataGridView的+行+集合+(http://www.google.com/search ?q =行+不能+编程+添加+ + DataGridView的+行+集合+当+控制+是+数据绑定) –

相关问题