Question : PowerShell and .NET - Calling Methods


Busily chipping away at understanding PowerShell, but being a complete non-programmer occasionally makes things really odd...

Anyway, perhaps some one already knows this one and I can stop trying to make up reasons.

I really like having access to the .NET Framework, really quite shiny and can do things that were a pain in the proverbial in VbScript. But...

When using classes and their associated methods in the .NET Framework how do you know how to properly call them (in advance, without my usual Trial and Error approach)?

For example, I can call a method in the DNS class like this:

[System.Net.DNS]::GetHostByAddress("")

And / Or access the values returned with:

([System.Net.DNS]::GetHostByAddress("")).HostName

All fine so far, but then I go and pick on another class, we'll take Ping this time, sticking in the networking theme. Because it's somewhat consistent I wanted to do this:

[System.Net.NetworkInformation.Ping]::Send("P>")

Send being the method under the Ping class that seemed entirely sound. Doesn't work, of course. Instead I have to create an object:

$Ping = New-Object System.Net.NetworkInformation.Ping
$Ping.Send("")

So, hmmm, anyone happen to know why? If it's not a horribly long answer involving many concepts that I just don't want to get ;)

Chris

Answer : PowerShell and .NET - Calling Methods

First... Let me tell you I am NOT a developer... never was and never will be :) That said while learning Powershell I have learned some qwerks of .NET. One of those qwerks is a static method.

A static method is a function that can be call on a class without having to create and instance of a class. In your case you were calling ping() as if it is a static method using [type]::Method().

If you look at the class http://msdn2.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx

It does not have any static methods. This means you have to create an instance of the class using the New-Object CMDLet

For future... Learning to use the MSDN website has help tremendously and understanding some of the trivial developer terms that go with it...

I have a blog post here that covers the basics. Its old.. I should update it :)
http://bsonposh.com/modules/wordpress/?p=10

Random Solutions  
 
programming4us programming4us