Powershell仅从PSObject返回值

时间:2014-08-25 23:36:56

标签: powershell

我使用以下内容来获取tracert的状态 目前它将它存储在一个New-Object psobject中,但我遇到的问题是,当我尝试过滤Status时只想返回Success我得到以下返回而不是@ {Status = Success},我该如何删除@ {Status =}来自结果?

function Invoke-Trace() {
   param(
   [string[]]$targetIP,
   $BeginHop = 1,
   $EndHop = 30,
   $timeout = 1000,
   [switch]$GetHostname
   )

   $addrtype = [System.Net.Sockets.AddressFamily]::InterNetwork;
   if($v6.ispresent) {
   $addrtype = [System.Net.Sockets.AddressFamily]::InterNetworkV6;
   }

   $targetIPActual = $null;
   if(![net.ipaddress]::TryParse($targetIP, [ref]$targetIPActual)) {
     $target = [net.dns]::GetHostEntry($targetIP);
     $targetIPActual = $target.addresslist | where {$_.addressfamily -eq $addrtype} |       select -First 1
   } else {
     $target = New-Object psobject -Property @{"HostName" = $targetIP.tostring()}
   }

   for($i = $BeginHop; $i -lt $EndHop; $i++) {

   $ping = new-object System.Net.NetworkInformation.ping;
   $pingo = new-object System.Net.NetworkInformation.PingOptions $i, $true;
   $sendbytes = @([byte][char]'a'..[byte][char]'z');
   $pr = $ping.Send($targetIPActual, $timeout, $sendbytes, $pingo);
   try {
       $rtn = New-Object psobject -Property @{
        "IP" = $pr.Address;
        "RoundtripTime" = $pr.RoundtripTime;
        "Status" = $pr.Status;
       }
   } catch {
       $rtn = New-Object psobject -Property @{
        "IP" = "*";
        "RoundtripTime" = $pr.RoundtripTime;
        "Status" = $pr.Status;
    }
}

try {
    if($GetHostname.ispresent) {
        Add-Member -InputObject $rtn -MemberType NoteProperty -Name Hostname -Value ([net.dns]::GetHostEntry($pr.Address).hostname)
    }
} catch{}

$rtn;

#$pr
try { 
    if($pr.Address.tostring() -eq $targetIPActual) { break; }
    } catch{}
  }
}

1 个答案:

答案 0 :(得分:2)

如果您的$rtnPSObject并且您只想返回它的一个属性,则不要返回整个对象。 #$pr上方的行是您返回对象的位置,因此您可以执行此操作:

$rtn.Status

我有点不清楚你为什么要把它放在那个对象中,因为你似乎不想使用它,但我只是假设你有理由给你这个快速回答。随意编辑您的问题,并澄清是否有可能缺少的东西。