Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function Ping-Hostname {
- [cmdletbinding()]
- param(
- [parameter(Mandatory=$true,
- ValueFromPipeline=$true,
- ParameterSetName="String")]
- [String[]]
- $HostName,
- [parameter(Mandatory=$true,
- ValueFromPipeline=$true,
- ParameterSetName="Object")]
- [PSObject[]]
- $Computers
- )
- Begin{
- $ComputersArray = New-Object System.Collections.ArrayList
- }
- Process{
- If($HostName){
- ForEach($Name in $HostName){
- $Computer = [PSCustomObject]@{
- Name = $Name
- Job = (Test-Connection -ComputerName $Name -Count 5 -BufferSize 16 -AsJob)
- Return = $null
- ScriptTypeObject = $false #Tag object to return only hostname string in final processing
- }
- $ComputersArray.Add($Computer) | Out-Null
- }
- }
- Else{
- ForEach($Computer in $Computers){
- Add-Member -InputObject $Computer -Name 'Job' -MemberType NoteProperty -Value (Test-Connection -ComputerName $Computer.Name -Count 5 -BufferSize 16 -AsJob) -Force
- Add-Member -InputObject $Computer -Name 'Return' -MemberType NoteProperty -Value $null -Force
- Add-Member -InputObject $Computer -Name 'ScriptTypeObject' -MemberType NoteProperty -Value $true -Force #Tag object to return full object in final processing
- $computersArray.Add($Computer) | Out-Null
- }
- }
- }
- End{
- $Result = New-Object System.Collections.ArrayList
- Get-Job | Wait-Job | Out-Null
- ForEach($Computer in $ComputersArray){
- If($Computer.Return -eq $null){
- $Computer.Return = Receive-Job $Computer.Job
- }
- }
- ForEach($Computer in $ComputersArray){
- If($Computer.Return | %{If($_.StatusCode -eq 0){$true}}){
- If($Computer.ScriptTypeObject -eq $false){ #Return only strings or full objects based on received input
- $Result.Add($Computer.Name) | Out-Null
- }
- Else{
- $Computer.PSObject.Members.Remove('Job')
- $Computer.PSObject.Members.Remove('Return')
- $Computer.PSObject.Members.Remove('ScriptTypeObject')
- $Result.Add($Computer) | Out-Null
- }
- }
- }
- Get-Job | Where-Object {$_.Command -like 'Test-Connection'} | Remove-Job
- $Result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment