PSCustomObject返回奇怪的输出 [英] PSCustomobject returrning strange output

查看:8
本文介绍了PSCustomObject返回奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,它应该在三台服务器上运行一个测试连接和一个测试网络连接,现在我正在使用"localhost"进行测试

问题是,我希望它至少会进行两次"测试连接",它确实做到了,但输出非常奇怪(从逻辑角度来看是合理的,但从输出角度来看则不是)

代码如下: 如果我使用COUNT参数并将其设置为1次,则输出是正确的它显示进行测试的一台PC,如果我将其设置为2,则输出出错

$computers="localhost"


  foreach ($pc in $computers){

      $test_connection = Test-Connection -ComputerName $pc -Count 2 

      $test_netconnection = Test-NetConnection $pc -Port 1433   

         #}else{ Write-Host "can't reach $pc"}   

        [pscustomobject] @{
                           LocalPC             =$test_connection.PSComputerName
                          'Tested-Server'      =$test_netconnection.ComputerName
                           Bytes               =$test_connection.buffersize
                           Time                =$test_connection.ResponseTime
                           RemotePort          =$test_netconnection.RemotePort
                           TcpTestSucceeded    =$test_netconnection.TcpTestSucceeded

                           }| ft -AutoSize #end of Customobject
                           }                                                                                                          
                           #}#end of foreach loop    
pause

输出:

WARNING: TCP connect to (::1 : 1433) failed
WARNING: TCP connect to (127.0.0.1 : 1433) failed

LocalPC            Tested-Server Bytes    Time   RemotePort TcpTestSucceeded
-------            ------------- -----    ----   ---------- ----------------
{LEVL-01, LEVL-01} localhost     {32, 32} {0, 0}       1433            False
还显示了第二个奇怪的输出,即我添加了Erroraction参数 (但我会把它留到另一个职位上) 如何将这两个"本地PC"输出转换为一个输出?

非常感谢您的帮助

推荐答案

根据评论,您的问题是$test_connection最终包含两个对象,每个对象对应一个测试结果。您可以使用数组索引运算符[0]选择特定对象的结果,也可以使用Select -First 1获得第一个结果。我推荐使用后者,因为如果结果恰好为空,则不太可能引发异常。

作为进一步的建议,您可以使用Measure-Object -Average返回执行这两个测试所需时间的平均结果。我还建议您不要在循环中使用Format-Table,而是将结果整理到一个变量中,然后在结尾对该变量使用它。

以下是代码中的修订:

$computers="localhost"

$Result = foreach ($pc in $computers){

    $test_connection = Test-Connection -ComputerName $pc -Count 2
    $test_netconnection = Test-NetConnection $pc -Port 1433   

    [pscustomobject] @{
        LocalPC          = ($test_connection | Select -First 1).PSComputerName
        'Tested-Server'  = $test_netconnection.ComputerName
        Bytes            = ($test_connection | Select -First 1).Bytes
        Time             = ($test_connection | Measure-Object -Average ResponseTime).Average
        RemotePort       = $test_netconnection.RemotePort
        TcpTestSucceeded = $test_netconnection.TcpTestSucceeded
    }
}                                                                                                          

$Result | Ft -AutoSize

这篇关于PSCustomObject返回奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆