PowerShell – Pinging Devices From Selected Cells in Form GridView Results in Error

  Kiến thức lập trình

I have a form with a gridview that is populated from AD. The idea is to select any cells from the gridview with hostnames and then get the results of Test-Connection for each computer and send that off to another gridview, e.g.:

$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'

This works so long as the computers return successful ping. However, a failed ping will return the following error:

“Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named ‘op_Addition’.”

If I declare the variable instead to, say, $Computers = ‘Computer1′,’Computer2′,’Computer3’,… then the grid opens as expected with both success and failed results.

Obviously, the issue is with variable $Computers = $datagridview1.SelectedCells.Value. Just not sure what I need to do to make it work.

New contributor

William is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT