Well, my Ping-Computer cmdlet didn’t work. Dang. But this is a useful opportunity to cover some debugging techniques! I’ve got a lot of places where things COULD be going wrong. When I run Ping-Computer, no matter what name I provide, I get no output – no result at all. That’s bad. So, I want to change something to see what the problem is. I want to change the cmdlet so that, no matter WHAT happens, SOME output gets created. Here’s my code revision:
For Each result In Searcher.Get
If result.GetPropertyValue(“StatusCode”) Then
WriteDebug(“Successful ping of ” & ThisName)
WriteObject(ThisName)
Else
WriteDebug(“Could not ping ” & ThisName)
WriteObject(“NO”)
End If
Next
I only added ONE line of code, which I’ve highlighted above. I shut down PowerShell and re-build my cmdlet, generating a fresh DLL. Then I reopen PowerShell, and try again:
PS C:\> ping-computer localhost
NO
PS C:\>
Cool! I got output! So my cmdlet sort of works – but it’s not pinging correctly. That’s really good news, because I’ve narrowed the problem down to just one or two lines of code. So, the first thing I notice is that the WMI query in my cmdlet code is using a variable. I need to see what’s inside of that variable – another quick cmdlet modification will tell me:
For Each ThisName In _Name
WriteDebug(“Attempting to ping ” & ThisName)
WriteObject(“Attempting to ping ” & ThisName)
Dim Query As SelectQuery
You may be asking why the WriteDebug() isn’t sufficient. Well, the host I’m using to run this doesn’t actually display what’s been output to WriteDebug… so I’ve just duplicated the line using WriteOutput, just so I can see what’s going on. Now, I recompile, rerun PowerShell, and try again:
PS C:\> ping-computer localhost
Attempting to ping localhost
NO
PS C:\>
Don’t forget: You’ll need to re-add the PSSnapIn when you restart PowerShell. And my test proves that my variable is being populated correctly for my WMI query. Cool. But… it still isn’t working right. Oh, wait… DUH. I see the problem, now:
If result.GetPropertyValue(“StatusCode”) ThenThis should be:
If result.GetPropertyValue(“StatusCode”) = 0 Then
Instead. So, I’ll fix that and take out my little test code, rebuild, relaunch, re-add, and try again:
PS C:\> add-pssnapin primaltoys
PS C:\> ping-computer localhost
localhost
PS C:\>
AWESOME!! It worked, outputting the name of the successfully-pinged computer. Why wouldn’t I just have it output “True” or something? Here’s why: Supposed I have a file named C:\Computers.txt, listing one computer name on each line of the file. Like this:
sapienteched
server2
localhost
Then I could do this:
PS C:\> get-content c:\computers.txt | ping-computer
sapienteched
server2
localhost
PS C:\>
Oh, wait… it was only supposed to output names it could ping, and Server2 shouldn’t have been on the list. I don’t have a Server2. Dang again – back to debugging… in my next installment!