• No results found

Objects are all around us. A car is an object with a collection of separate parts, such as a steering wheel, accelerator pedal and brakes. To drive the car, we can use the parts to steer, accelerate and slow/stop the vehicle. We can now divide the car (object) into two distinct concepts.

 A collection of parts

 Uses of the parts to change the car’s behavior

Now, apply this object model to the Windows Operating System.

A Windows Service object has a collection of parts called Properties. Properties represent the state of a service, such as the service name and status. The service status can be changed by using object Methods. Object Methods allow you to start or stop a service. Collectively, properties and methods are called object Members.

Members

Properties Methods

Service Name Start() Status Stop()

Note: Method names can be easily distinguished from property names as they are always appended with a pair of smooth brackets ‘()’.

Task 1: List Object Information (Get-Member Cmdlet)

The .NET object framework is self-descriptive. All objects hold information that describes their structure. You can interrogate any .NET object and list its properties and methods within PowerShell without needing to refer to the online MSDN Class Library.

You can achieve this by passing the object through the pipeline, to the Get-Member Cmdlet.

Pipeline operations will be covered in detail in another lesson.

1. Get a list of process objects using the Service Cmdlet and pipe them to the Get-Member Cmdlet.

This will list the members (properties & methods) of this type of object.

Get-Service | Get-Member

2. Alternatively, you can choose not to use the pipeline and employ the Get-Member Cmdlet’s InputObject parameter. This command however lists the members of the collectin of pipeline data as a whole, rather than the individual items in the collection.

Get-Member –InputObject (Get-Service)

The top of the output lists the type name of the object(s). In the first case when piping to Ger-Member, you can see it is a System.ServiceProcess.ServiceController type of object.

TypeName: System.ServiceProcess.ServiceController

The next piece of information displayed is the collection of members (properties and methods). The output below displays three columns of member information: the name, membertype and definition.

Name MemberType Definition ---- --- ---

Name AliasProperty Name = ServiceName

RequiredServices AliasProperty RequiredServices = ServicesDependedOn Disposed Event System.EventHandler Disposed(System.Object,

GetLifetimeService Method System.Object GetLifetimeService() GetType Method type GetType()

InitializeLifetimeService Method System.Object InitializeLifetimeService() Pause Method System.Void Pause()

CanPauseAndContinue Property System.Boolean CanPauseAndContinue {get;}

CanShutdown Property System.Boolean CanShutdown {get;}

CanStop Property System.Boolean CanStop {get;}

Container Property System.ComponentModel.IContainer Container

DependentServices Property System.ServiceProcess.ServiceController[]

DisplayName Property System.String DisplayName {get;set;}

MachineName Property System.String MachineName {get;set;}

ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceName Property System.String ServiceName {get;set;}

ServicesDependedOn Property System.ServiceProcess.ServiceController[]

ServiceType Property System.ServiceProcess.ServiceType Site Property System.ComponentModel.ISite Site Status Property

3. The PowerShell code below returns the number of members that a System.ServiceProcess.ServiceController object contains.

Note: Pipeline operations will be covered in more detail in the next lesson).

You can see that there are 32 members of a System.ServiceProcess.ServiceController object.

Get-Service | Get-Member | Measure-Object -Property MemberType

Count : 32

4. It is possible to shorten the output from this Cmdlet by listing only the properties.

Get-Service | Get-Member –MemberType property

5. It is also possible to shorten the output by listing only the methods.

Get-Service | Get-Member –MemberType method

6. Now that you have uncovered the object’s members, you can use them to access state information using properties and manipulate the object using methods.

Task 2: Access Object Members

To access information stored in object properties or execute object methods, the dot (.) character is used to separate the object name from the member name. This is referred to as dot-notation.

1. Select a single service object by filtering the output of the Get-Service Cmdlet using the Name parameter and assign it to a variable.

$ALGService = Get-Service –Name alg

2. Type the variable name to confirm that you have referenced the correct service.

By default, three properties of the service object are displayed: Status, Name and DisplayName.

$ALGService

Status Name DisplayName --- ---- ---

Running ALG Application Layer Gateway Service

3. Type a dot (.) character directly after the variable name and repeatedly press the Tab key.

The member names for this object type will be displayed one after the other.

4. Press Enter to display the information stored in one of the properties.

$ALGService.DisplayName

Application Layer Gateway Service

5. Type the variable name again, followed by a dot, and type Start(). Press Enter.

Note: Be sure to append smooth brackets ‘()’ after the method name.

$ALGService.Start()

6. Type the variable name to view the service status.

Note that the status is still stopped. This is because the state of the service was saved at the instant you assigned it to a variable in step 1. Following the assignment, the state has not been updated.

7. To update the status property, execute the object’s Refresh() method.

$ALGService.Refresh()

8. The status property should now display Running.

$ALGService

Status Name DisplayName --- ---- ---

Running ALG Application Layer Gateway Service

9. Let’s see another example of accessing object members. Assign a string to a variable and pass it through the pipeline to Get-Member to discover the string object’s members.

Alternatively, you can use the alias for Get-Member (gm).

$strMyName = “My name is Chris”

$strMyName | Get-Member

10. You can also just pipe the string directly to the Get-Member Cmdlet. Both commands in steps 8 and 9 produce the same output.

“My name is Chris” | Get-Member

11. The object type name returned is System.String. This type has 2 properties and 32 methods. The length property stores the number of characters in the string. In this case, the string consists of 16 characters.

$strMyName.length 16

Alternatively, call the property using the string, rather than the variable. Again, both commands produce identical output.

(“My name is Chris”).length 16

Note: Even though the parenthesis are not required above, it makes sense to have them since it applies to other types of commands where this is not possible without parenthesis.

Try calling a few of the object methods.

o The Split() method splits the string on every occurrence of a space character and returns an array.

o The Substring() method returns a part of the string. This method requires input parameters to be provided within the parenthesis to represent the startIndex.

$strMyName.Substring(11) Chris

o The Replace() method replaces a substring of characters with another. This method requires two input parameters:

 The string to find

 The string to replace it with

$strMyName.Replace("Chris","John") My name is John

Note: The $strMyName variable is never modified by any of the methods and still contains the original string.

Task 3: Use the *-Object Cmdlets

PowerShell has a group of Cmdlets that can manipulate any type of object. This Cmdlet is typically used in a pipeline operation. Pipeline operations will be covered in detail in another lesson.

1. List the *-Object Cmdlets.

Get-Command –noun Object

CommandType Name Definition --- ---- ---

Cmdlet Compare-Object Compare-Object [-ReferenceObject…

Cmdlet ForEach-Object ForEach-Object [-Process] <Scrip…

Cmdlet Group-Object Group-Object [[-Property] <Objec…

Cmdlet Measure-Object Measure-Object [[-Property] <Str…

Cmdlet New-Object New-Object [-TypeName] <String>…

Cmdlet Select-Object Select-Object [[-Property] <Obje…

Cmdlet Sort-Object Sort-Object [[-Property] <Object…

Cmdlet Tee-Object Tee-Object [-FilePath] <String>…

Cmdlet Where-Object Where-Object [-FilterScript] <Sc…

2. Use the Sort-Object Cmdlet to sort a list of file and folders by their lastwritetime property.

Get-ChildItem –Path C:\Windows | Sort-Object –Property LastWriteTime

3. Find Process objects with more than 500 open handles using the Where-Object Cmdlet.

Get-Process | Where-Object {$_.handles –gt 500}

4. Return the total file size of a directory in KB.

Get-ChildItem –Path ‘C:\Program Files’ –Recurse | Measure-Object –Property length -Sum

Task 4: Add Object Members

PowerShell allows you to add user-defined members to existing objects.

For example, you want to display the number of threads within a process object. The Add-Member Cmdlet can be used to add a new property in which to store information.

1. To add a new property, return a process object using the Get-Process Cmdlet and assign it to a variable.

$process = Get-Process -Name lsass

2. Confirm that the Process objects’ Threads property contains a list of thread objects.

$process.Threads

Since the Threads property is an array object, it has a count property that stores the number of thread objects contained within it.

3. Use the Add-Member Cmdlet to add a new scriptproperty called ThreadCount to the process object. Note that the InputObject parameter is used to supply the object Add-Member operates on.

The Value property argument is contained in a set of curly brackets '{}'. This is called a scriptblock and can contain any PowerShell code. The $this variable refers to the current object instance stored in the $process variable.

Add-Member –InputObject $process -MemberType scriptproperty -Name ThreadCount ` –Value {$this.Threads.Count} -PassThru

4. Access the new property to display the number of threads running in this particular process.

$process.ThreadCount 15

Exercise 4: The .NET Object Model

The .NET (pronounced ‘dot net’) framework consists of a library of code that enables interaction with many aspects of the Windows Operating system and an environment in which the code runs. The separation of the runtime environment (Common Language Runtime) and the underlying Windows operating system ensures .NET code is unable to directly compromise operating system security and stability.