从表单 GridView 中的选定单元格 Ping 设备会导致错误

问题描述 投票:0回答:1

我有一个带有从 AD 填充的网格视图的表单。这个想法是从带有主机名的网格视图中选择任何单元格,然后获取每台计算机的测试连接结果并将其发送到另一个网格视图,例如:

$Computers = $datagridview1.SelectedCells.Value

$Success = Test-Connection -ComputerName $Computers -Count 1 -ErrorAction SilentlyContinue -ErrorVariable errors | Select-Object @{ Name = 'Computer'; Expression = { $_.address } }, IPv4Address,
                       @{ Name = 'Result'; Expression = { 'Success' } }
        
$Failed = $Errors.Exception.Message | Where-Object { $_ -Match "Computer '(.+?)'" } |
Select-Object @{ Name = 'Computer'; Expression = { $Matches.1 } },
              @{ Name = 'IPv4Address'; Expression = { "N/A" } },
              @{ Name = 'Result'; Expression = { 'Failed' } }   
        
$Success + $Failed | Out-GridView -Title 'Ping Status'

只要计算机返回成功的 ping,此操作就有效。但是,失败的 ping 将返回以下错误:

方法调用失败,因为 [System.Management.Automation.PSObject] 不包含名为“op_Addition”的方法。

如果我将变量声明为

$Computers = 'Computer1','Computer2','Computer3',...
,那么网格将按预期打开,并显示成功和失败的结果。

显然,问题在于变量

$Computers = $datagridview1.SelectedCells.Value
。只是不确定我需要做什么才能使其发挥作用。

powershell
1个回答
0
投票

问题很可能发生在

$Success
是单个
PSObject
时,然后它将失败并出现您所看到的错误:

$Computers = 'google.com', 'doesnotexist.xyz'

$Success = Test-Connection -ComputerName $Computers -Count 1 -ErrorAction SilentlyContinue -ErrorVariable errors |
    Select-Object @(
        @{ Name = 'Computer'; Expression = { $_.Address }}
        'IPv4Address'
        @{ Name = 'Result'; Expression = { 'Success' }})

$Failed = $Errors.TargetObject |
    Select-Object @(
        @{ Name = 'Computer'; Expression = { $_ }}
        @{ Name = 'IPv4Address'; Expression = { "N/A" }}
        @{ Name = 'Result'; Expression = { 'Failed' }})

$Success + $Failed # Method invocation failed because [System.Management.Automation.PSObject]...

解决问题的方法很简单,只要用

数组子表达式运算符
$Success
包裹
@(...)
,这样即使
$Success
中没有项目也不会失败:

@($Success) + $Failed

而且,更好的方法是包裹整个表达式:

@(
    Test-Connection -ComputerName $Computers -Count 1 -ErrorAction SilentlyContinue -ErrorVariable errors |
        Select-Object @(
            @{ Name = 'Computer'; Expression = { $_.Address }}
            'IPv4Address'
            @{ Name = 'Result'; Expression = { 'Success' }})

    $Errors.TargetObject |
        Select-Object @(
            @{ Name = 'Computer'; Expression = { $_ }}
            @{ Name = 'IPv4Address'; Expression = { "N/A" }}
            @{ Name = 'Result'; Expression = { 'Failed' }})
) | Out-GridView -Title 'Ping Status'
© www.soinside.com 2019 - 2024. All rights reserved.