Skip to content

Test-Connection shows unwanted output when DNS not resolved on Powershell 7.0.0 #12147

Closed

Description

@chvol

Test-Connection -Quiet -Count 1 Hostname
gives output

Test-Connection: Testing connection to computer 'Hostname' failed: Cannot resolve the target name.

Expected behaviour would be

False

In a code block like
$comps | ForEach-Object -Process { if (Test-Connection $_.Name -Quiet -Count 1) {Write-Output "$($_.Name) on"} else {Write-Output "$($_.Name) off"} }
this gives output
Test-Connection: Testing connection to computer 'Hostname' failed: Cannot resolve the target name. Hostname off

Again, the extra output is unwanted, given the Quiet flag.

Activity

  1. added
    Issue-Question
    on Mar 18, 2020
  2. vexx32 commented on Mar 18, 2020

    @vexx32
    Collaborator

    🤔 This is kinda weird. We shouldn't be surfacing any hostname resolution errors...

    This code path handles the hostname resolution:

    private bool TryResolveNameOrAddress(
    string targetNameOrAddress,
    out string resolvedTargetName,
    [NotNullWhen(true)]
    out IPAddress? targetAddress)
    {
    resolvedTargetName = targetNameOrAddress;
    IPHostEntry hostEntry;
    if (IPAddress.TryParse(targetNameOrAddress, out targetAddress))
    {
    if ((IPv4 && targetAddress.AddressFamily != AddressFamily.InterNetwork)
    || (IPv6 && targetAddress.AddressFamily != AddressFamily.InterNetworkV6))
    {
    string message = StringUtil.Format(
    TestConnectionResources.NoPingResult,
    resolvedTargetName,
    TestConnectionResources.TargetAddressAbsent);
    Exception pingException = new PingException(message, null);
    ErrorRecord errorRecord = new ErrorRecord(
    pingException,
    TestConnectionExceptionId,
    ErrorCategory.ResourceUnavailable,
    resolvedTargetName);
    WriteError(errorRecord);
    return false;
    }
    if (ResolveDestination)
    {
    hostEntry = Dns.GetHostEntry(targetNameOrAddress);
    resolvedTargetName = hostEntry.HostName;
    }
    else
    {
    resolvedTargetName = targetAddress.ToString();
    }
    }
    else
    {
    try
    {
    hostEntry = Dns.GetHostEntry(targetNameOrAddress);
    if (ResolveDestination)
    {
    resolvedTargetName = hostEntry.HostName;
    hostEntry = Dns.GetHostEntry(hostEntry.HostName);
    }
    }
    catch (Exception ex)
    {
    string message = StringUtil.Format(
    TestConnectionResources.NoPingResult,
    resolvedTargetName,
    TestConnectionResources.CannotResolveTargetName);
    Exception pingException = new PingException(message, ex);
    ErrorRecord errorRecord = new ErrorRecord(
    pingException,
    TestConnectionExceptionId,
    ErrorCategory.ResourceUnavailable,
    resolvedTargetName);
    WriteError(errorRecord);
    return false;
    }
    if (IPv6 || IPv4)
    {
    targetAddress = GetHostAddress(hostEntry);
    if (targetAddress == null)
    {
    string message = StringUtil.Format(
    TestConnectionResources.NoPingResult,
    resolvedTargetName,
    TestConnectionResources.TargetAddressAbsent);
    Exception pingException = new PingException(message, null);
    ErrorRecord errorRecord = new ErrorRecord(
    pingException,
    TestConnectionExceptionId,
    ErrorCategory.ResourceUnavailable,
    resolvedTargetName);
    WriteError(errorRecord);
    return false;
    }
    }
    else
    {
    targetAddress = hostEntry.AddressList[0];
    }
    }
    return true;
    }

    As you can see, we're catching everything in there. Not sure why you'd be getting hostname resolution errors here, unless you're using a different Test-Connection command. There are only two cases you should be getting errors from this cmdlet -- when you provide a $null hostname, or when you provide an IP address that doesn't match the requested switch (i.e., providing an IPv6 address and specifying -IPv4 or vice versa).

    Just to be sure, can you grab the output from Get-Command Test-Connection so we can see what it's calling?

  3. chvol commented on Mar 18, 2020

    @chvol
    Author

    Get-Command Test-Connection

    CommandType     Name                                               Version    Source
    -----------     ----                                               -------    ------
    Cmdlet          Test-Connection                                    7.0.0.0    Microsoft.PowerShell.Management
    
  4. vexx32 commented on Mar 18, 2020

    @vexx32
    Collaborator

    Can you post the result from $PSVersionTable as well, please, so we have any necessary OS / other info? Thanks! 😊

  5. vexx32 commented on Mar 18, 2020

    @vexx32
    Collaborator

    Oh, I see it.

    try
    {
    hostEntry = Dns.GetHostEntry(targetNameOrAddress);
    if (ResolveDestination)
    {
    resolvedTargetName = hostEntry.HostName;
    hostEntry = Dns.GetHostEntry(hostEntry.HostName);
    }
    }
    catch (Exception ex)
    {
    string message = StringUtil.Format(
    TestConnectionResources.NoPingResult,
    resolvedTargetName,
    TestConnectionResources.CannotResolveTargetName);
    Exception pingException = new PingException(message, ex);
    ErrorRecord errorRecord = new ErrorRecord(
    pingException,
    TestConnectionExceptionId,
    ErrorCategory.ResourceUnavailable,
    resolvedTargetName);
    WriteError(errorRecord);
    return false;
    }

    We should definitely be just returning false here.

  6. iSazonov commented on Mar 18, 2020

    @iSazonov
    Collaborator

    Issue is here

    if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress))
    {
    return;

  7. added
    Issue-Bug
    and removed
    Issue-Question
    on Mar 18, 2020
  8. vexx32 commented on Mar 18, 2020

    @vexx32
    Collaborator

    We catch the hostname resolution error in the method and call WriteError() -- there's nothing that can be done outside the method call itself other than writing false to output. The issue here is that the error still shows in -Quiet mode, so we'd need to handle that in the method.

  9. iSazonov commented on Mar 19, 2020

    @iSazonov
    Collaborator

    Quiet parameter can be used in interactive session too. If user don't want to get error SilentlyContinue exists.

  10. vexx32 commented on Mar 19, 2020

    @vexx32
    Collaborator

    -Quiet should do what it says on the tin, in my opinion. 🤷‍♂

    If it's erroring, it's not quiet. A user shouldn't have to ask for quiet twice in one command call. That just leads to frustration, at best. If they want the error, they can simply not use -Quiet.

  11. SeeminglyScience commented on Mar 19, 2020

    @SeeminglyScience
    Contributor

    Rain Sallow (/u/ta11ow) (@vexx32) btw the get host entry call is part of why the command sometimes doesn't respond to stop processing requests.

  12. vexx32 commented on Mar 19, 2020

    @vexx32
    Collaborator

    That's a very good point... Is there an async/cancellable method for that one you know of?

    EDIT: Nevermind, found one! https://docs.microsoft.com/en-us/dotnet/api/system.net.dns.gethostentryasync?view=netcore-3.1

    I think we can incorporate that one... Not sure exactly how, but seems like it should be doable to add some code to make it respect cancellation requests.

  13. SeeminglyScience commented on Mar 19, 2020

    @SeeminglyScience
    Contributor

    Rain Sallow (/u/ta11ow) (@vexx32) Since there's no cancel, all you can really do is something like:

    private CancellationTokenSource _cancel;
    
    // ...
    
    private IPHostEntry GetHostEntryWithCancel(string hostNameOrAddress)
    {
        var task = Dns.GetHostEntryAsync(hostNameOrAddress);
        var waitHandles = new[] { ((IAsyncResult)task).AsyncWaitHandle, _cancel.Token.WaitHandle };
        if (WaitHandle.WaitAny(waitHandles) == 1)
        {
            throw new OperationCanceledException();
        }
    
        return task.GetAwaiter().GetResult();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugResolution-FixedWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions