ondrovic
ondrovic

Reputation: 1175

Powershell Return only value from PSObject

I am using the following to get the status of tracert Currently it stores it in a New-Object psobject but the problem I am running into is that when I try and filter on Status wanting just to return Success I get the following returned instead @{Status=Success}, how can I remove the @{Status=} from around the results?

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{}
  }
}

Upvotes: 0

Views: 1510

Answers (1)

briantist
briantist

Reputation: 47792

If your $rtn is a PSObject and you want to just return one property of it, then don't return the whole object. The line above #$pr is where your object is being returned, so you could do this instead:

$rtn.Status

It's a bit unclear to me why you're putting it in that object in the first place since you don't seem to want to use it, but I'm just going to assume you have a reason and give you this quick answer. Feel free to edit your question and clarify if there's something that might be missing.

Upvotes: 2

Related Questions