This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
forked from RamblingCookieMonster/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Invoke-Ping.ps1
906 lines (762 loc) · 42.2 KB
/
Invoke-Ping.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
Function Invoke-Ping
{
<#
.SYNOPSIS
Ping or test connectivity to systems in parallel
.DESCRIPTION
Ping or test connectivity to systems in parallel
Default action will run a ping against systems
If Quiet parameter is specified, we return an array of systems that responded
If Detail parameter is specified, we test WSMan, RemoteReg, RPC, RDP and/or SMB
.PARAMETER ComputerName
One or more computers to test
.PARAMETER Quiet
If specified, only return addresses that responded to Test-Connection
.PARAMETER Detail
Include one or more additional tests as specified:
WSMan via Test-WSMan
RemoteReg via Microsoft.Win32.RegistryKey
RPC via WMI
RDP via port 3389
SMB via \\ComputerName\C$
* All tests
.PARAMETER Timeout
Time in seconds before we attempt to dispose an individual query. Default is 20
.PARAMETER Throttle
Throttle query to this many parallel runspaces. Default is 100.
.PARAMETER NoCloseOnTimeout
Do not dispose of timed out tasks or attempt to close the runspace if threads have timed out
This will prevent the script from hanging in certain situations where threads become non-responsive, at the expense of leaking memory within the PowerShell host.
.EXAMPLE
Invoke-Ping Server1, Server2, Server3 -Detail *
# Check for WSMan, Remote Registry, Remote RPC, RDP, and SMB (via C$) connectivity against 3 machines
.EXAMPLE
$Computers | Invoke-Ping
# Ping computers in $Computers in parallel
.EXAMPLE
$Responding = $Computers | Invoke-Ping -Quiet
# Create a list of computers that successfully responded to Test-Connection
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Invoke-Ping-Test-in-b553242a
.FUNCTIONALITY
Computers
#>
[cmdletbinding(DefaultParameterSetName='Ping')]
param(
[Parameter( ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]$ComputerName,
[Parameter( ParameterSetName='Detail')]
[validateset("*","WSMan","RemoteReg","RPC","RDP","SMB")]
[string[]]$Detail,
[Parameter(ParameterSetName='Ping')]
[switch]$Quiet,
[int]$Timeout = 20,
[int]$Throttle = 100,
[switch]$NoCloseOnTimeout
)
Begin
{
#http://gallery.technet.microsoft.com/Run-Parallel-Parallel-377fd430
function Invoke-Parallel {
[cmdletbinding(DefaultParameterSetName='ScriptBlock')]
Param (
[Parameter(Mandatory=$false,position=0,ParameterSetName='ScriptBlock')]
[System.Management.Automation.ScriptBlock]$ScriptBlock,
[Parameter(Mandatory=$false,ParameterSetName='ScriptFile')]
[ValidateScript({test-path $_ -pathtype leaf})]
$ScriptFile,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[Alias('CN','__Server','IPAddress','Server','ComputerName')]
[PSObject]$InputObject,
[PSObject]$Parameter,
[switch]$ImportVariables,
[switch]$ImportModules,
[int]$Throttle = 20,
[int]$SleepTimer = 200,
[int]$RunspaceTimeout = 0,
[switch]$NoCloseOnTimeout = $false,
[int]$MaxQueue,
[validatescript({Test-Path (Split-Path $_ -parent)})]
[string]$LogFile = "C:\temp\log.log",
[switch] $Quiet = $false
)
Begin {
#No max queue specified? Estimate one.
#We use the script scope to resolve an odd PowerShell 2 issue where MaxQueue isn't seen later in the function
if( -not $PSBoundParameters.ContainsKey('MaxQueue') )
{
if($RunspaceTimeout -ne 0){ $script:MaxQueue = $Throttle }
else{ $script:MaxQueue = $Throttle * 3 }
}
else
{
$script:MaxQueue = $MaxQueue
}
Write-Verbose "Throttle: '$throttle' SleepTimer '$sleepTimer' runSpaceTimeout '$runspaceTimeout' maxQueue '$maxQueue' logFile '$logFile'"
#If they want to import variables or modules, create a clean runspace, get loaded items, use those to exclude items
if ($ImportVariables -or $ImportModules)
{
$StandardUserEnv = [powershell]::Create().addscript({
#Get modules and snapins in this clean runspace
$Modules = Get-Module | Select -ExpandProperty Name
$Snapins = Get-PSSnapin | Select -ExpandProperty Name
#Get variables in this clean runspace
#Called last to get vars like $? into session
$Variables = Get-Variable | Select -ExpandProperty Name
#Return a hashtable where we can access each.
@{
Variables = $Variables
Modules = $Modules
Snapins = $Snapins
}
}).invoke()[0]
if ($ImportVariables) {
#Exclude common parameters, bound parameters, and automatic variables
Function _temp {[cmdletbinding()] param() }
$VariablesToExclude = @( (Get-Command _temp | Select -ExpandProperty parameters).Keys + $PSBoundParameters.Keys + $StandardUserEnv.Variables )
Write-Verbose "Excluding variables $( ($VariablesToExclude | sort ) -join ", ")"
# we don't use 'Get-Variable -Exclude', because it uses regexps.
# One of the veriables that we pass is '$?'.
# There could be other variables with such problems.
# Scope 2 required if we move to a real module
$UserVariables = @( Get-Variable | Where { -not ($VariablesToExclude -contains $_.Name) } )
Write-Verbose "Found variables to import: $( ($UserVariables | Select -expandproperty Name | Sort ) -join ", " | Out-String).`n"
}
if ($ImportModules)
{
$UserModules = @( Get-Module | Where {$StandardUserEnv.Modules -notcontains $_.Name -and (Test-Path $_.Path -ErrorAction SilentlyContinue)} | Select -ExpandProperty Path )
$UserSnapins = @( Get-PSSnapin | Select -ExpandProperty Name | Where {$StandardUserEnv.Snapins -notcontains $_ } )
}
}
#region functions
Function Get-RunspaceData {
[cmdletbinding()]
param( [switch]$Wait )
#loop through runspaces
#if $wait is specified, keep looping until all complete
Do {
#set more to false for tracking completion
$more = $false
#Progress bar if we have inputobject count (bound parameter)
if (-not $Quiet) {
Write-Progress -Activity "Running Query" -Status "Starting threads"`
-CurrentOperation "$startedCount threads defined - $totalCount input objects - $script:completedCount input objects processed"`
-PercentComplete $( Try { $script:completedCount / $totalCount * 100 } Catch {0} )
}
#run through each runspace.
Foreach($runspace in $runspaces) {
#get the duration - inaccurate
$currentdate = Get-Date
$runtime = $currentdate - $runspace.startTime
$runMin = [math]::Round( $runtime.totalminutes ,2 )
#set up log object
$log = "" | select Date, Action, Runtime, Status, Details
$log.Action = "Removing:'$($runspace.object)'"
$log.Date = $currentdate
$log.Runtime = "$runMin minutes"
#If runspace completed, end invoke, dispose, recycle, counter++
If ($runspace.Runspace.isCompleted) {
$script:completedCount++
#check if there were errors
if($runspace.powershell.Streams.Error.Count -gt 0) {
#set the logging info and move the file to completed
$log.status = "CompletedWithErrors"
Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
foreach($ErrorRecord in $runspace.powershell.Streams.Error) {
Write-Error -ErrorRecord $ErrorRecord
}
}
else {
#add logging details and cleanup
$log.status = "Completed"
Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
}
#everything is logged, clean up the runspace
$runspace.powershell.EndInvoke($runspace.Runspace)
$runspace.powershell.dispose()
$runspace.Runspace = $null
$runspace.powershell = $null
}
#If runtime exceeds max, dispose the runspace
ElseIf ( $runspaceTimeout -ne 0 -and $runtime.totalseconds -gt $runspaceTimeout) {
$script:completedCount++
$timedOutTasks = $true
#add logging details and cleanup
$log.status = "TimedOut"
Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1]
Write-Error "Runspace timed out at $($runtime.totalseconds) seconds for the object:`n$($runspace.object | out-string)"
#Depending on how it hangs, we could still get stuck here as dispose calls a synchronous method on the powershell instance
if (!$noCloseOnTimeout) { $runspace.powershell.dispose() }
$runspace.Runspace = $null
$runspace.powershell = $null
$completedCount++
}
#If runspace isn't null set more to true
ElseIf ($runspace.Runspace -ne $null ) {
$log = $null
$more = $true
}
#log the results if a log file was indicated
if($logFile -and $log){
($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] | out-file $LogFile -append
}
}
#Clean out unused runspace jobs
$temphash = $runspaces.clone()
$temphash | Where { $_.runspace -eq $Null } | ForEach {
$Runspaces.remove($_)
}
#sleep for a bit if we will loop again
if($PSBoundParameters['Wait']){ Start-Sleep -milliseconds $SleepTimer }
#Loop again only if -wait parameter and there are more runspaces to process
} while ($more -and $PSBoundParameters['Wait'])
#End of runspace function
}
#endregion functions
#region Init
if($PSCmdlet.ParameterSetName -eq 'ScriptFile')
{
$ScriptBlock = [scriptblock]::Create( $(Get-Content $ScriptFile | out-string) )
}
elseif($PSCmdlet.ParameterSetName -eq 'ScriptBlock')
{
#Start building parameter names for the param block
[string[]]$ParamsToAdd = '$_'
if( $PSBoundParameters.ContainsKey('Parameter') )
{
$ParamsToAdd += '$Parameter'
}
$UsingVariableData = $Null
# This code enables $Using support through the AST.
# This is entirely from Boe Prox, and his https://github.com/proxb/PoshRSJob module; all credit to Boe!
if($PSVersionTable.PSVersion.Major -gt 2)
{
#Extract using references
$UsingVariables = $ScriptBlock.ast.FindAll({$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]},$True)
If ($UsingVariables)
{
$List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]'
ForEach ($Ast in $UsingVariables)
{
[void]$list.Add($Ast.SubExpression)
}
$UsingVar = $UsingVariables | Group Parent | ForEach {$_.Group | Select -First 1}
#Extract the name, value, and create replacements for each
$UsingVariableData = ForEach ($Var in $UsingVar) {
Try
{
$Value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPath -ErrorAction Stop
$NewName = ('$__using_{0}' -f $Var.SubExpression.VariablePath.UserPath)
[pscustomobject]@{
Name = $Var.SubExpression.Extent.Text
Value = $Value.Value
NewName = $NewName
NewVarName = ('__using_{0}' -f $Var.SubExpression.VariablePath.UserPath)
}
$ParamsToAdd += $NewName
}
Catch
{
Write-Error "$($Var.SubExpression.Extent.Text) is not a valid Using: variable!"
}
}
$NewParams = $UsingVariableData.NewName -join ', '
$Tuple = [Tuple]::Create($list, $NewParams)
$bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance"
$GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl',$bindingFlags))
$StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast,@($Tuple))
$ScriptBlock = [scriptblock]::Create($StringScriptBlock)
Write-Verbose $StringScriptBlock
}
}
$ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param($($ParamsToAdd -Join ", "))`r`n" + $Scriptblock.ToString())
}
else
{
Throw "Must provide ScriptBlock or ScriptFile"; Break
}
Write-Debug "`$ScriptBlock: $($ScriptBlock | Out-String)"
Write-Verbose "Creating runspace pool and session states"
#If specified, add variables and modules/snapins to session state
$sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
if ($ImportVariables)
{
if($UserVariables.count -gt 0)
{
foreach($Variable in $UserVariables)
{
$sessionstate.Variables.Add( (New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList $Variable.Name, $Variable.Value, $null) )
}
}
}
if ($ImportModules)
{
if($UserModules.count -gt 0)
{
foreach($ModulePath in $UserModules)
{
$sessionstate.ImportPSModule($ModulePath)
}
}
if($UserSnapins.count -gt 0)
{
foreach($PSSnapin in $UserSnapins)
{
[void]$sessionstate.ImportPSSnapIn($PSSnapin, [ref]$null)
}
}
}
#Create runspace pool
$runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host)
$runspacepool.Open()
Write-Verbose "Creating empty collection to hold runspace jobs"
$Script:runspaces = New-Object System.Collections.ArrayList
#If inputObject is bound get a total count and set bound to true
$global:__bound = $false
$allObjects = @()
if( $PSBoundParameters.ContainsKey("inputObject") ){
$global:__bound = $true
}
#Set up log file if specified
if( $LogFile ){
New-Item -ItemType file -path $logFile -force | Out-Null
("" | Select Date, Action, Runtime, Status, Details | ConvertTo-Csv -NoTypeInformation -Delimiter ";")[0] | Out-File $LogFile
}
#write initial log entry
$log = "" | Select Date, Action, Runtime, Status, Details
$log.Date = Get-Date
$log.Action = "Batch processing started"
$log.Runtime = $null
$log.Status = "Started"
$log.Details = $null
if($logFile) {
($log | convertto-csv -Delimiter ";" -NoTypeInformation)[1] | Out-File $LogFile -Append
}
$timedOutTasks = $false
#endregion INIT
}
Process {
#add piped objects to all objects or set all objects to bound input object parameter
if( -not $global:__bound ){
$allObjects += $inputObject
}
else{
$allObjects = $InputObject
}
}
End {
#Use Try/Finally to catch Ctrl+C and clean up.
Try
{
#counts for progress
$totalCount = $allObjects.count
$script:completedCount = 0
$startedCount = 0
foreach($object in $allObjects){
#region add scripts to runspace pool
#Create the powershell instance, set verbose if needed, supply the scriptblock and parameters
$powershell = [powershell]::Create()
if ($VerbosePreference -eq 'Continue')
{
[void]$PowerShell.AddScript({$VerbosePreference = 'Continue'})
}
[void]$PowerShell.AddScript($ScriptBlock).AddArgument($object)
if ($parameter)
{
[void]$PowerShell.AddArgument($parameter)
}
# $Using support from Boe Prox
if ($UsingVariableData)
{
Foreach($UsingVariable in $UsingVariableData) {
Write-Verbose "Adding $($UsingVariable.Name) with value: $($UsingVariable.Value)"
[void]$PowerShell.AddArgument($UsingVariable.Value)
}
}
#Add the runspace into the powershell instance
$powershell.RunspacePool = $runspacepool
#Create a temporary collection for each runspace
$temp = "" | Select-Object PowerShell, StartTime, object, Runspace
$temp.PowerShell = $powershell
$temp.StartTime = Get-Date
$temp.object = $object
#Save the handle output when calling BeginInvoke() that will be used later to end the runspace
$temp.Runspace = $powershell.BeginInvoke()
$startedCount++
#Add the temp tracking info to $runspaces collection
Write-Verbose ( "Adding {0} to collection at {1}" -f $temp.object, $temp.starttime.tostring() )
$runspaces.Add($temp) | Out-Null
#loop through existing runspaces one time
Get-RunspaceData
#If we have more running than max queue (used to control timeout accuracy)
#Script scope resolves odd PowerShell 2 issue
$firstRun = $true
while ($runspaces.count -ge $Script:MaxQueue) {
#give verbose output
if($firstRun){
Write-Verbose "$($runspaces.count) items running - exceeded $Script:MaxQueue limit."
}
$firstRun = $false
#run get-runspace data and sleep for a short while
Get-RunspaceData
Start-Sleep -Milliseconds $sleepTimer
}
#endregion add scripts to runspace pool
}
Write-Verbose ( "Finish processing the remaining runspace jobs: {0}" -f ( @($runspaces | Where {$_.Runspace -ne $Null}).Count) )
Get-RunspaceData -wait
if (-not $quiet) {
Write-Progress -Activity "Running Query" -Status "Starting threads" -Completed
}
}
Finally
{
#Close the runspace pool, unless we specified no close on timeout and something timed out
if ( ($timedOutTasks -eq $false) -or ( ($timedOutTasks -eq $true) -and ($noCloseOnTimeout -eq $false) ) ) {
Write-Verbose "Closing the runspace pool"
$runspacepool.close()
}
#collect garbage
[gc]::Collect()
}
}
}
Write-Verbose "PSBoundParameters = $($PSBoundParameters | Out-String)"
$bound = $PSBoundParameters.keys -contains "ComputerName"
if(-not $bound)
{
[System.Collections.ArrayList]$AllComputers = @()
}
}
Process
{
#Handle both pipeline and bound parameter. We don't want to stream objects, defeats purpose of parallelizing work
if($bound)
{
$AllComputers = $ComputerName
}
Else
{
foreach($Computer in $ComputerName)
{
$AllComputers.add($Computer) | Out-Null
}
}
}
End
{
#Built up the parameters and run everything in parallel
$params = @($Detail, $Quiet)
$splat = @{
Throttle = $Throttle
RunspaceTimeout = $Timeout
InputObject = $AllComputers
parameter = $params
}
if($NoCloseOnTimeout)
{
$splat.add('NoCloseOnTimeout',$True)
}
Invoke-Parallel @splat -ScriptBlock {
$computer = $_.trim()
$detail = $parameter[0]
$quiet = $parameter[1]
#They want detail, define and run test-server
if($detail)
{
Try
{
#Modification of jrich's Test-Server function: https://gallery.technet.microsoft.com/scriptcenter/Powershell-Test-Server-e0cdea9a
Function Test-Server{
[cmdletBinding()]
param(
[parameter(
Mandatory=$true,
ValueFromPipeline=$true)]
[string[]]$ComputerName,
[switch]$All,
[parameter(Mandatory=$false)]
[switch]$CredSSP,
[switch]$RemoteReg,
[switch]$RDP,
[switch]$RPC,
[switch]$SMB,
[switch]$WSMAN,
[switch]$IPV6,
[Management.Automation.PSCredential]$Credential
)
begin
{
$total = Get-Date
$results = @()
if($credssp -and -not $Credential)
{
Throw "Must supply Credentials with CredSSP test"
}
[string[]]$props = write-output Name, IP, Domain, Ping, WSMAN, CredSSP, RemoteReg, RPC, RDP, SMB
#Hash table to create PSObjects later, compatible with ps2...
$Hash = @{}
foreach($prop in $props)
{
$Hash.Add($prop,$null)
}
function Test-Port{
[cmdletbinding()]
Param(
[string]$srv,
$port=135,
$timeout=3000
)
$ErrorActionPreference = "SilentlyContinue"
$tcpclient = new-Object system.Net.Sockets.TcpClient
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
if(-not $wait)
{
$tcpclient.Close()
Write-Verbose "Connection Timeout to $srv`:$port"
$false
}
else
{
Try
{
$tcpclient.EndConnect($iar) | out-Null
$true
}
Catch
{
write-verbose "Error for $srv`:$port`: $_"
$false
}
$tcpclient.Close()
}
}
}
process
{
foreach($name in $computername)
{
$dt = $cdt= Get-Date
Write-verbose "Testing: $Name"
$failed = 0
try{
$DNSEntity = [Net.Dns]::GetHostEntry($name)
$domain = ($DNSEntity.hostname).replace("$name.","")
$ips = $DNSEntity.AddressList | %{
if(-not ( -not $IPV6 -and $_.AddressFamily -like "InterNetworkV6" ))
{
$_.IPAddressToString
}
}
}
catch
{
$rst = New-Object -TypeName PSObject -Property $Hash | Select -Property $props
$rst.name = $name
$results += $rst
$failed = 1
}
Write-verbose "DNS: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($failed -eq 0){
foreach($ip in $ips)
{
$rst = New-Object -TypeName PSObject -Property $Hash | Select -Property $props
$rst.name = $name
$rst.ip = $ip
$rst.domain = $domain
if($RDP -or $All)
{
####RDP Check (firewall may block rest so do before ping
try{
$socket = New-Object Net.Sockets.TcpClient($name, 3389) -ErrorAction stop
if($socket -eq $null)
{
$rst.RDP = $false
}
else
{
$rst.RDP = $true
$socket.close()
}
}
catch
{
$rst.RDP = $false
Write-Verbose "Error testing RDP: $_"
}
}
Write-verbose "RDP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
#########ping
if(test-connection $ip -count 2 -Quiet)
{
Write-verbose "PING: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
$rst.ping = $true
if($WSMAN -or $All)
{
try{############wsman
Test-WSMan $ip -ErrorAction stop | Out-Null
$rst.WSMAN = $true
}
catch
{
$rst.WSMAN = $false
Write-Verbose "Error testing WSMAN: $_"
}
Write-verbose "WSMAN: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($rst.WSMAN -and $credssp) ########### credssp
{
try{
Test-WSMan $ip -Authentication Credssp -Credential $cred -ErrorAction stop
$rst.CredSSP = $true
}
catch
{
$rst.CredSSP = $false
Write-Verbose "Error testing CredSSP: $_"
}
Write-verbose "CredSSP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
}
if($RemoteReg -or $All)
{
try ########remote reg
{
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $ip) | Out-Null
$rst.remotereg = $true
}
catch
{
$rst.remotereg = $false
Write-Verbose "Error testing RemoteRegistry: $_"
}
Write-verbose "remote reg: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
if($RPC -or $All)
{
try ######### wmi
{
$w = [wmi] ''
$w.psbase.options.timeout = 15000000
$w.path = "\\$Name\root\cimv2:Win32_ComputerSystem.Name='$Name'"
$w | select none | Out-Null
$rst.RPC = $true
}
catch
{
$rst.rpc = $false
Write-Verbose "Error testing WMI/RPC: $_"
}
Write-verbose "WMI/RPC: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
if($SMB -or $All)
{
#Use set location and resulting errors. push and pop current location
try ######### C$
{
$path = "\\$name\c$"
Push-Location -Path $path -ErrorAction stop
$rst.SMB = $true
Pop-Location
}
catch
{
$rst.SMB = $false
Write-Verbose "Error testing SMB: $_"
}
Write-verbose "SMB: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
}
else
{
$rst.ping = $false
$rst.wsman = $false
$rst.credssp = $false
$rst.remotereg = $false
$rst.rpc = $false
$rst.smb = $false
}
$results += $rst
}
}
Write-Verbose "Time for $($Name): $((New-TimeSpan $cdt ($dt)).totalseconds)"
Write-Verbose "----------------------------"
}
}
end
{
Write-Verbose "Time for all: $((New-TimeSpan $total ($dt)).totalseconds)"
Write-Verbose "----------------------------"
return $results
}
}
#Build up parameters for Test-Server and run it
$TestServerParams = @{
ComputerName = $Computer
ErrorAction = "Stop"
}
if($detail -eq "*"){
$detail = "WSMan","RemoteReg","RPC","RDP","SMB"
}
$detail | Select -Unique | Foreach-Object { $TestServerParams.add($_,$True) }
Test-Server @TestServerParams | Select -Property $( "Name", "IP", "Domain", "Ping" + $detail )
}
Catch
{
Write-Warning "Error with Test-Server: $_"
}
}
#We just want ping output
else
{
Try
{
#Pick out a few properties, add a status label. If quiet output, just return the address
$result = $null
if( $result = @( Test-Connection -ComputerName $computer -Count 2 -erroraction Stop ) )
{
$Output = $result | Select -first 1 -Property Address,
IPV4Address,
IPV6Address,
ResponseTime,
@{ label = "STATUS"; expression = {"Responding"} }
if( $quiet )
{
$Output.address
}
else
{
$Output
}
}
}
Catch
{
if(-not $quiet)
{
#Ping failed. I'm likely making inappropriate assumptions here, let me know if this is the case : )
if($_ -match "No such host is known")
{
$status = "Unknown host"
}
elseif($_ -match "Error due to lack of resources")
{
$status = "No Response"
}
else
{
$status = "Error: $_"
}
"" | Select -Property @{ label = "Address"; expression = {$computer} },
IPV4Address,
IPV6Address,
ResponseTime,
@{ label = "STATUS"; expression = {$status} }
}
}
}
}
}
}