我试图在报告中添加ping失败的服务器,但异常不是将结果添加到datagridview ..我哪里出错了?
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 :(得分: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
阻止中,current object variable $_
拥有异常对象,而不是Test-Connection
的结果(无论如何都失败了,因此没有&#39} ; t首先产生一个结果)。请改为使用变量$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)
}