Methods

PowerShell uses objects to represent the items in data stores or the state of the computer. For example, FileInfo objects represent the files in file system drives and ProcessInfo objects represent the processes on the computer.

Objects have properties, which store data about the object, and methods that let you change the object.

To get the methods of any object, use the Get-Member cmdlet. Use its MemberType property with a value of "Method".

Get-Process | Get-Member -MemberType Method TypeName: System.Diagnostics.Process Name MemberType Definition ---- ---------- ---------- BeginErrorReadLine Method System.Void BeginErrorReadLine() BeginOutputReadLine Method System.Void BeginOutputReadLine() ... Kill Method System.Void Kill() Refresh Method System.Void Refresh() Start Method bool Start() ToString Method string ToString() WaitForExit Method bool WaitForExit(int milliseconds), ... WaitForInputIdle Method bool WaitForInputIdle(int millisecon...

To perform or "invoke" a method of an object, type a dot (.), the method name, and a set of parentheses "()". If the method has arguments, place the argument values inside the parentheses. The parentheses are required for every method call, even when there are no arguments. If the method takes multiple arguments, they should be separated by commas.

$notepad = Get-Process notepad $notepad.Kill() #shortened by combining the above statements. (Get-Process Notepad).Kill()

Another very useful method is the Replace method of strings. The Replace method, replaces text within a string. In the example below, the dot (.) can be placed immediately after the end quote of the string.

'this is rocket science'.Replace('rocket', 'rock') this is rock science

A method definition might have one or more method signatures, which are like the parameter sets of PowerShell cmdlets. The signatures show all of the valid formats of commands to invoke the method.

the CopyTo method of the FileInfo class contains the following two method signatures:

CopyTo(String destFileName) CopyTo(String destFileName, Boolean overwrite) (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt") (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt", $true)