Test-Ping Function

//Test-Ping Function
Test-Ping Function 2016-02-03T17:39:04+00:00

The Toolkit Forums Toolkit Extensions Test-Ping Function

  • Author
    Posts
  • That_annoying_guy
    Participant
    Post count: 42
    #1058 |

    <pre class=”brush: powershell; gutter: true; first-line: 1; highlight: []; html-script: false”>

    #region Function Test-Ping
    Function Test-Ping {
    <#
    .SYNOPSIS
    Pings IP or DNS Name
    .DESCRIPTION
    Sends ICMP echo request packets ("pings") to one or more computers using .Net's [system.net.networkinformation.ping]
    Returns $true or $false
    This function tries to mimic PS v4's Test-connection somewhat
    FYI: PSADT limits itself to PS v2 and .net 2.0 for maximum compatibility
    .PARAMETER ComputerName
    CN,IPAddress,__SERVER,Server,Destination
    Name or IP the target computer.
    .PARAMETER Count
    Number of echo ICMP requests sent. The default value is 4.
    .PARAMETER BufferSize
    Buffer used with this command. Default is 32 bytes.
    .PARAMETER TimeToLive
    Maximum number of times the ICMP echo message can be forwarded before reaching its destination.
    If the packet does not reach its destination after being forwarded the specified number of times,
    the packet is discarded and the ICMP echo request fails. When this happens, the Status is set to TtlExpired.
    Range is 1-255. Default is 64
    .PARAMETER TimeOut
    Maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message from target.
    .PARAMETER DontFragment
    If true and the total packet size exceeds the maximum packet size that can be transmitted by one of the routing
    nodes between the local and remote computers, the ICMP echo request fails.
    When this happens, the Status is set to PacketTooBig.
    .PARAMETER PassThru
    Returns a PSObject.
    Use the following to obtain list of properties that are available:
    Test-Ping -Name $envComputerName -PassThru | select *
    .PARAMETER ContinueOnError
    Continue if an error is encountered. Default is: $true.
    .EXAMPLE
    Test-Ping -ComputerName 'MyServerName' -PassThru
    .EXAMPLE
    Test-Ping -ComputerName '10.10.0.31' -PassThru
    .EXAMPLE
    Test-Ping 'dontexixt'
    (Returns $false)
    .NOTES
    Tested on Win7 english. Should work on XP and up.
    Depends on Write-log and Write-FunctionHeaderOrFooter
    CAVEAT: If given %ComputerName% as target, will use IP6 to ping
    .LINK

    #>
    [CmdletBinding()]
    Param (
    [Parameter(Mandatory=$true, HelpMessage="CN,IPAddress,__SERVER,Server,Destination")]
    [Alias('CN','__SERVER','IPAddress','Server')]
    [ValidateNotNullOrEmpty()]
    [string]$ComputerName,
    [Parameter(Mandatory=$false, HelpMessage="Number of echo ICMP requests sent. The default value is 4")]
    [ValidateNotNullOrEmpty()]
    [Int]$Count = 4,
    [Parameter(Mandatory=$false)]
    [ValidateNotNullOrEmpty()]
    [Int]$BufferSize = 32,
    [Parameter(Mandatory=$false, HelpMessage="Number of hops before it gives up")]
    [ValidateNotNullOrEmpty()]
    [Alias('TTL')]
    [Int]$TimeToLive = 64,
    [Parameter(Mandatory=$false, HelpMessage="In milliseconds")]
    [ValidateNotNullOrEmpty()]
    [Int32]$timeout = 1000,
    [Parameter(Mandatory=$false)]
    [ValidateNotNullOrEmpty()]
    [Bool]$DontFragment = $false,
    [Parameter(Mandatory=$false, HelpMessage="Returns a PSObject instead of [Bool]")]
    [ValidateNotNullOrEmpty()]
    [switch]$PassThru
    )
    Begin {
    [string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
    Write-FunctionHeaderOrFooter -CmdletName ${CmdletName} -CmdletBoundParameters $PSBoundParameters -Header
    }
    Process {
    Try {
    [Bool]$resolve = $true
    [system.net.NetworkInformation.PingOptions]$options = new-object system.net.networkinformation.pingoptions
    $options.TTL = $TimeToLive
    $options.DontFragment = $DontFragment
    [array]$buffer = ([system.text.encoding]::ASCII).getbytes("a"*$buffersize)
    Try {
    #Must test $ComputerName to make sure it converts to a IP address or else .Ping will blow up
    $IpAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) #String hostNameOrAddress
    $ping = new-object system.net.networkinformation.ping
    #$reply = $ping.Send($IpAddress,$timeout,$buffer,$options) #Can't use $IpAddress. It's an array of IP4+IP6 of ALL adapters, Real and virtual.
    $reply = $ping.Send($ComputerName,$timeout,$buffer,$options)
    [String]$hostname = ([System.Net.Dns]::GetHostEntry($ComputerName)).hostname #might fail if RDNS is broken, so…
    } Catch {
    $reply = @{} # Create empty hash table
    $reply.status = 'FailDnsLookup'
    $ErrorMessage = "$($_.Exception.Message) $($_.Exception.InnerException)"
    Write-Log -Message "$ErrorMessage" -Severity 3 -Source ${CmdletName}
    }
    If ($reply.status -eq "Success"){ $IsAlive = $true } else { $IsAlive = $false }

    $info = @{} # Create empty hash table
    $info.InputGiven = $ComputerName
    $info.status = $reply.status #Success,TtlExpired,PacketTooBig
    $info.RoundtripTime = $reply.RoundtripTime #In MilliSeconds
    $info.Hostname = $hostname
    $info.AddressUsed = $reply.Address
    $info.AddressAll = $IpAddress #Ping $envComputerName to see multiple addresses (ip4/ip6)
    $info.TimeToLive = $options.TTL
    $info.DontFragment = $options.DontFragment
    $info.IsAlive = $IsAlive
    $info.Buffer = $buffer
    $info.ErrorMessage = $ErrorMessage

    If ($PassThru) {
    New-Object PSObject -Property $info -ErrorAction SilentlyContinue
    } Else {
    Write-Output $IsAlive
    }
    }
    Catch {
    Write-Log -Message "Failed ping to see if [$ComputerName] is alive on the network: $($_.Exception.Message) $($_.Exception.InnerException)" -Severity 3 -Source ${CmdletName}
    If ($PassThru) {
    If ($info) { New-Object PSObject -Property $info -ErrorAction SilentlyContinue }
    } Else {
    Write-Output $false
    }
    }
    }
    End {
    Write-FunctionHeaderOrFooter -CmdletName ${CmdletName} -Footer
    }
    }
    #endregion Function Test-Ping

    • This topic was modified 1 year, 9 months ago by  That_annoying_guy. Reason: trying the Powershell tag
  • That_annoying_guy
    Participant
    Post count: 42

    I give up.
    This is gibberish: https://codex.wordpress.org/Writing_Code_in_Your_Posts

    There are no examples on how to post PowerShell code.
    We get no Preview of what it going to look like AND we get 2 tries, that’s it. Post is locked.

    A video would help b/c there are no “Crayons” to play with as mentioned in http://psappdeploytoolkit.com/forums/topic/what-are-toolkit-extensions/

  • That_annoying_guy
    Participant
    Post count: 42

    Mo,

    If you are interested, I have the following that I could post once this is:

    Function Test-TCPPort {
    Function Get-Shortcuts {
    Function Add-ToLocalGroup {
    Function Get-LocalUserAccount {
    Function Get-OsNickName {
    Function Get-ComputerOU {
    Function Parse-CMTLogFile {
    Function Get-NicInfo {

  • That_annoying_guy
    Participant
    Post count: 42

    [Deleted!]

  • Muhammad Mashwani
    Keymaster
    Post count: 118

    The problem is with WordPress. The WordPress bbPress plugin used to do the forums uses the back tick to denote a code block. Since backtick is actually part of the PowerShell language, it messes up PowerShell code. The only way to post PowerShell code properly would be to replace all instances of the backtick with the HTML character that codes for it. I’m looking at migrating to something else because it’s getting on my nerves as well.

  • Muhammad Mashwani
    Keymaster
    Post count: 118

    The problem is with WordPress. The WordPress bbPress plugin used to do the forums uses the back tick to denote a code block. Since backtick is actually part of the PowerShell language, it messes up PowerShell code. The only way to post PowerShell code properly would be to replace all instances of the backtick with the HTML character that codes for it. I’m looking at migrating to something else because it’s getting on my nerves as well.

  • That_annoying_guy
    Participant
    Post count: 42

    <pre class=”brush: powershell; gutter: true; first-line: 1; highlight: []; html-script: false”>

    <code>					Try {
    		            	$GroupList.Add($ADSIObject.sAMAccountName.ToString() + &quot;\&quot; + $Group.Value.Split(&quot;\&quot;)[1], $True)
    					} Catch [System.ArgumentException] { #Item has already been added. Key in dictionary
    						Write-log -Message &quot;$(Resolve-Error)&quot; -Severity 2 -Source ${CmdletName} -DebugMessage
    						Write-log &quot;WARNING: ADSIObject [$($ADSIObject.sAMAccountName.ToString())] has Duplicate membership in group [$($Group.Value)]&quot; -Severity 2 -Source ${CmdletName}
    					} Catch {
    						Write-log -Message &quot;</code>

    $SID [$SID] $(Resolve-Error)” -Severity 2 -Source ${CmdletName}
    }`

  • That_annoying_guy
    Participant
    Post count: 42

    Ok, PowerShell Pre tags don’t work and the code tags converts code to &useless

    If you want code for Test-IsGroupMember and Convert-ObjectNameToDN you’ll need to tell me where I can post other than WontPress.

    PS: I’ve been asked to create a function for permissions for my local fork (aka your issue #141)
    It would be a wrapper for SetACL.exe (https://helgeklein.com/setacl/) or the COM object.
    Would you be interested?

You must be logged in to reply to this topic.