Static methods

As static properties, static methods do not require that an instance of a class is created.

MSDN shows static methods using an S symbol in the leftmost column. For example, the System.Net.NetworkInformation.NetworkInterface class has a number of static methods. The first of these is shown in the following screenshot:

PowerShell is also able to list these methods using Get-Member with the Static switch, as shown here:

PS> [System.Net.NetworkInformation.NetworkInterface] | Get-Member -MemberType Method -Static

TypeName: System.Net.NetworkInformation.NetworkInterface

Name MemberType Definition
---- ---------- ----------
Equals Method static bool Equals(System.Object objA, System.Object objB)
GetAllNetworkInterfaces Method static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces()
GetIsNetworkAvailable Method static bool GetIsNetworkAvailable()
ReferenceEquals Method static bool ReferenceEquals(System.Object objA, System.Object objB)

Static methods are accessed using the following generalized notation:

[<TypeName>]::<MethodName>(<ArgumentList>) 

As the GetAllNetworkInterfaces method does not require arguments, it may be called as follows:

[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() 

The parentheses at the end of the statement must be included to tell PowerShell that this is a method.

As was seen with static properties, both type and method may be assigned to variables:

$type = [System.Net.NetworkInformation.NetworkInterface]
$methodName = 'GetAllNetworkInterfaces'
$type::$methodName()

The parentheses are not part of the method name.

Static methods often require arguments. The System.IO.Path class has many static methods that require arguments, as shown in the following screenshot:

Arguments are passed in as a comma-separated list. For example, the ChangeExtension method may be used, as follows:

[System.IO.Path]::ChangeExtension("C:
one.exe", "bak") 

An array containing a list of arguments cannot be directly supplied. Consider the following example:

$argumentList = "C:
one.exe", "bak" 
[System.IO.Path]::ChangeExtension($argumentList) 

If a list of arguments is to be supplied from a variable, the method object must be invoked:

$argumentList = "C:
one.exe", "bak" 
[System.IO.Path]::ChangeExtension.Invoke($argumentList) 

The method object (because everything is an object) is accessed by omitting the parentheses that normally follow the name of the method:

PS> [System.IO.Path]::ChangeExtension

OverloadDefinitions

-------------------
static string ChangeExtension(string path, string extension)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.85