Using methods

As we mentioned previously, methods effect a change in state. That may be a change to the object associated with the method, or it may take the object and convert it into something else.

Methods are called using the following notation in PowerShell:

<Object>.Method() 

If a method expects to have arguments (or parameters), the notation becomes the following:

<Object>.Method(Argument1, Argument2) 

When the method is called without parentheses, PowerShell will show the overload definitions. The overload definitions are a list of the different sets of arguments that can be used with a method. For example, the Substring method of System.String has two definitions:

PS> 'thisString'.Substring

OverloadDefinitions
-------------------
string Substring(int startIndex)
string Substring(int startIndex, int length)

An example of a method that takes an object and converts it into something else is shown here. In this case, a date is converted into a string:

PS> $date = Get-Date "01/01/2010"
PS> $date.ToLongDateString()
01 January 2010

An example of a method that changes a state might be a TCP socket. TCP connections must be opened before data can be sent over a network:

$tcpClient = New-Object System.Net.Sockets.TcpClient
$tcpClient.Connect("127.0.0.1", 135)

A TCP client is created, then an attempt is made to connect to the RPC endpoint mapper port (TCP/135) on the localhost.

The Connect method does not return anything (although it will throw an error if the connection fails). It affects the state of the object and is reflected by the Connected property:

PS> $tcpClient.Connected
True

The state of the object may be changed again by calling the Close method to disconnect:

$tcpClient.Close()

An example of a method that takes arguments might be the ToString method on a DateTime object. Get-Date can be used to create a DateTime object:

PS> (Get-Date).ToString('u')
2016-12-08 21:18:49Z

In the preceding example, the letter u is one of the standard date and time format strings (https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx) and represents a universal sortable date/time pattern. The same result may be achieved by using the Format parameter of Get-Date:

PS> Get-Date -Format u
2016-12-08 21:19:31Z

The advantage this method has over the parameter is that the date can be adjusted before conversion by using some of the other properties and methods:

(Get-Date).Date.AddDays(-1).ToString('u') 

The result of this command will be the start of yesterday (midnight, one day before today).

..................Content has been hidden....................

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