Back to Basics: Understanding PowerShell Objects

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is not just a shell to run scripts. It’s the backbone of most IT professionals’ workflows, but there are some things you need to know before gaining an understanding of what happens when PowerShell invokes cmdlets and objects in your script. I’ll help demystify this process by explaining how PowerShell works behind the scenes.

The “powershell list object properties” is a command-line tool that allows users to view the properties of PowerShell objects. The “Back to Basics: Understanding PowerShell Objects” will discuss what these properties are and how to use them.

Back to Basics: Understanding PowerShell Objects

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

Now you’re tinkering with the output and making your own string. The only method to do this is to utilize the ForEach-Object cmdlet, which is shown below. PowerShell executes the function Write-Host -ForegroundColor ‘Yellow’

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName “is running” for each object returned from Where-Object, as seen below.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

Now you’re tinkering with the output and making your own string. The only method to do this is to utilize the ForEach-Object cmdlet, which is shown below. PowerShell executes the function Write-Host -ForegroundColor ‘Yellow’

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName “is running” for each object returned from Where-Object, as seen below.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

Now you’re tinkering with the output and making your own string. The only method to do this is to utilize the ForEach-Object cmdlet, which is shown below. PowerShell executes the function Write-Host -ForegroundColor ‘Yellow’

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName “is running” for each object returned from Where-Object, as seen below.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

Now you’re tinkering with the output and making your own string. The only method to do this is to utilize the ForEach-Object cmdlet, which is shown below. PowerShell executes the function Write-Host -ForegroundColor ‘Yellow’

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName “is running” for each object returned from Where-Object, as seen below.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

Now you’re tinkering with the output and making your own string. The only method to do this is to utilize the ForEach-Object cmdlet, which is shown below. PowerShell executes the function Write-Host -ForegroundColor ‘Yellow’

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’ Where-Object -FilterScript

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName -Like “Windows*” -and

PowerShell is a robust programming language. But what is it about this scripting language that makes it so powerful? Objects in PowerShell What exactly are these mysterious items, and how does PowerShell interact with them? Keep an eye out for further information.

PowerShell is a shell and object-oriented programming language. This is a divergence from standard shells such as cmd and bash. Traditional shells concentrated on text, or strings, and although they are still helpful, they have limitations. In PowerShell, almost everything is an object.

In this tutorial, you’ll learn about several fundamental concepts in PowerShell when it comes to objects. Through useful example code and visuals, you’ll learn how to apply this information to your own scripts by the Conclusion of this tutorial.

If you prefer to study visually, you can view the video that goes along with this article below.

 

So hold on tight! You’re in for a fantastic adventure that will help you learn the PowerShell notion of objects!

Prerequisites

You’ll learn about objects in PowerShell using a hands-on approach in this tutorial. Windows PowerShell 5.1 or any version of PowerShell 6+ should work if you chose to follow along and attempt the code examples. All of the examples will, however, be run on Windows 10 build 1903 with Windows PowerShell 5.1.

Understanding an Object’s Anatomy

Objects may be found all across PowerShell. “What does an item look like?” you may be wondering. This first part will provide you an understanding of what an item is made out of. After you’ve gained a general understanding of what makes an object an object, you’ll be able to dig right into some code samples!

Using Get-Member to Find Object Members

Objects may be connected with a variety of different sorts of data. This information is commonly referred to as members in PowerShell. A general word for all information linked with an item is an object member.

The Get-Member cmdlet may be used to get information about an object (members). The Get-Member cmdlet is a useful PowerShell tool that enables you to locate accessible Properties, methods, and other features for any object.

Let’s imagine you want to see the members of a certain object returned by the Get-Service cmdlet. You may do so by passing the Get-Service command’s result to the Get-Member cmdlet, as seen below.

Get-Member | Get-Service -ServiceName ‘BITS’

Learn how to utilize the Get-Member cmdlet. This essay will make extensive use of it.

Get-Member may be piped from any PowerShell command that outputs output. Just keep in mind that this cmdlet should be the last in the pipeline since it will replace output with its own.

Types and Classes of Objects

Every object has a “schema,” without delving into too much information about object-oriented programming. The “schema” of an object is a kind of template that includes the blueprint for creating the object. A type is the name for that blueprint.

In PowerShell, each object has its own type. Each item has a blueprint that it was built from. A class defines the kind of an item. Consider the following: 9 is a number, Bluegill is a fish, Labrador is a dog, and so on. The type comes after the class.

Objects are instances of certain types of classes.

Don’t be concerned about delving too deeply into this subject. You generally don’t need to worry about semantics at this stage unless you’re a software engineer. It is, nonetheless, a crucial notion to understand at a fundamental level.

Properties

Property is the most fundamental idea to grasp when it comes to things. An object’s properties are qualities that characterize it. Many distinct properties may be connected to an object, each representing a different property.

The Get-Member cmdlet is one of the simplest methods to find out what attributes exist on objects. Get-Member will restrict the output returned to to objects if the MemberType argument is used, as seen below. You’ll also see that it shows the System object type. ServiceProcess. As well as ServiceController.

PS51> Get-Service | Get-Member -MemberType Property

Properties of the Get-Service objectProperties of the Get-Service object

Now, using the BITS service as an example, view the particular values of that object’s attributes using the code below. You can obtain the property names but not the values using the Get-Member cmdlet. However, you may view the property values using PowerShell’s Select-Object cmdlet.

StartType is a property on the object, as seen below. Although the object produced contains several members, the Select-Object cmdlet restricts the output to just display that property.

PS51> Get-Service -ServiceName ‘BITS’ | Select-Object -Property ‘StartType’

Type of BITS service startType of BITS service start

The most frequent component of an object you’ll interact with in PowerShell is its properties.

Aliases

Alias is a MemberType for certain properties. Aliases are fictitious names for properties. They may occasionally rename attributes to make them more understandable.

As an example, the Get-Service cmdlet may be used to create an object using aliases, as seen below. RequiredServices is an alias for the Property Name, and Property Name is an alias for the ServicesDependedOn property.

PS51> Get-Service | Get-Member -MemberType ‘AliasProperty’

Members of the AliasProperty class on service objectsMembers of the AliasProperty class on service objects

When a property has an alias, you may refer to its value instead of the original property name by using the alias name. A descriptive property like Name and RequiredServices, for example, is more obvious and simpler to express than ServiceName and ServicesDependedOn in this case.

Below is an example of how to refer to these aliases.

# Use the AliasProperty in place of an actual property name PS51> $Svc = Get-Service -ServiceName ‘BITS’ #Object you are working with PS51> $Svc.Name BITS PS51> $Svc.RequiredServices

The output should look like this. Keep in mind that the code is short, clear, and succinct once again. Whether you use the pseudonym or not, the following information remains the same:

The BITS service object's propertiesThe BITS service object’s properties

Methods

Properties are simply one part of the puzzle that makes up an object; methods are equally crucial to grasp. The activities that may be done on an object are referred to as methods. The Get-Member cmdlet may be used to find methods on an object, much like properties.

Set the MemberType argument value to Method to restrict Get-output Member’s to to methods, as illustrated below.

PS51> Get-Service | Get-Member -MemberType ‘Method’

On service objects, methodsOn service objects, methods

You’ll utilize methods much less often than properties as a novice.

Other Types of Members

The sorts of members that an object may have are not limited to properties, methods, and aliases. They will, however, be by far the most prevalent sort of member with whom you will interact.

A few more categories of members you can encounter are included below for completeness.

  • Script Property — These are used to determine the value of a property.
  • Note Property is a kind of property that is used to name static properties.
  • Property Sets — These are similar to aliases in that they include sets of properties. For example, in your Get-CompInfo method, you have a custom property named Specs. The property Specs is a subset of the properties Cpu, Mem, Hdd, and IP. Property sets are used to concatenate a collection of properties by providing a single property name.

The idea of object events should also be mentioned. The scope of this page does not include events.

In PowerShell, Working with Objects

Let’s get our hands dirty and start writing some code now that you have a basic idea of what an object is made out of.

Many PowerShell tasks generate output, but you don’t always need to see it all. That production must be limited or manipulated in some way. Fortunately, PowerShell includes a number of commands that may help you do this.

Let’s start with an example of using the Get-Service cmdlet to enumerate all services on the local machine, as shown below. As you can see from the output, there are a lot of distinct services (objects) returned.

PS51> Get-Service -ServiceName *

When it comes to the ServiceName argument, you may use a wildcard.When it comes to the ServiceName argument, you may use a wildcard.

Controlling the Properties of Returned Objects

Continuing with the Get-Service example, you may not need to examine all of the properties. Instead, you just need to look at the properties Status and DisplayName. The Select-Object cmdlet may be used to restrict the number of properties returned.

The Select-Object cmdlet “filters” the properties returned to the PowerShell pipeline using the Select-Object cmdlet. You may use the Property option to define a comma-delimited collection of one or more properties to return to “filter” object properties from being returned.

An example of merely returning the Status and DisplayName fields is shown below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’

The Status and DisplayName attributes are shown.The Status and DisplayName attributes are shown.

Organizing Objects

Perhaps you’re creating a report to display the status of services. You’d want to sort the objects returned by the value of the Status property to make it easier to absorb the information. You may accomplish this using the Sort-Object cmdlet.

The Sort-Object cmdlet collects all of the returned objects and then outputs them in the order you choose.

You may provide one or more attributes on the receiving objects from Get-Service to sort by using the Property argument of Sort-Object, for example. PowerShell will provide each object to the Sort-Object cmdlet, which will sort them by the property value.

Using the Decreasing switch argument of Sort-Object, you can appropriately retrieve all service objects sorted by their Status in descending order as seen below.

PS51> Get-Service -ServiceName * | Select-Object -Property ‘Status’,’DisplayName’ | Sort-Object -Property ‘Status’ -Descending

Sorting service objects by Status in decreasing order using Sort-ObjectSorting service objects by Status in decreasing order using Sort-Object

When using PowerShell, the pipe [|] is one of a few line continuation strategies you should employ. Use it instead of backticks.

Object Filtering

Perhaps you don’t want to view all of the services available on a system. Rather, you must restrict the output based on certain criteria. The Where-Object cmdlet is one technique to limit the amount of items returned.

The Where-Object cmdlet restricts the output of complete objects, while the Select-Object cmdlet limits the output of specified attributes.

The Where-Object cmdlet is comparable to the SQL WHERE clause in terms of functionality. It operates as a filter for the original source, returning only those objects that meet a set of criteria.

Perhaps you’ve determined that only objects with a Status property value of Running and a DisplayName property value that starts with A should be returned.

A Where-Object reference was introduced between Select-Object and Sort-Object in the pipeline order in the following code snippet. You may create whatever sort of query you want by using a scriptblock value with a needed condition created for each item to fulfill using the FilterScript argument.

If you wish to control how output is delivered to the console, use the Format-Table cmdlet.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object -FilterScript {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Format-Table -AutoSize

Object output formattingObject output formatting

Counting and Averaging Returned Objects

The Get-Service command returns a variety of items. You’ve filtered out a fraction of those items using the Where-Object cmdlet, but how many? The Measure-Object cmdlet is a new command in the PowerShell language.

The Measure-Object cmdlet is a PowerShell tool that may count how many objects it gets over the pipeline, among other things.

Perhaps you’d want to know how many items are returned after your combined instructions have completed. To obtain the total number of objects returned, send the final output to the Measure-Object cmdlet, as illustrated below.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object

When the instructions have finished executing, you’ll see that there were 21 objects returned, which were generated using the Get-Service cmdlet in this example.

Using Measure-Object to determine the number of objects returnedUsing Measure-Object to determine the number of objects returned

Perhaps you’re simply interested in the overall number of things returned. You may use the Select-Object cmdlet again since the Measure-Object command delivers the total number of items detected through a Count attribute. This time, though, just the Count attribute is returned.

PS51> Get-Service * | Select-Object -Property ‘Status’,’DisplayName’ | Where-Object {$_.Status -eq ‘Running’ -and $_.DisplayName -like “Windows*” | Sort-Object -Property ‘DisplayName’ -Descending | Measure-Object | # We start over again, filtering first, formatting last Select-Object -Property ‘Count’

Only the count attribute is returned.Only the count attribute is returned.

Using Loops to Take Action on Objects

You may use a loop to take action on each item as it is processed through the pipeline. In PowerShell, there are other types of loops, but we’ll stay with pipeline examples and look at the ForEach-Object cmdlet.

You may use the ForEach-Item cmdlet to take action on each object that flows into it. An example is the best way to describe this behavior.

Continuing with the Get-Service example, you could want to identify all operating services on a Windows PC with a name that begins with “Windows.” You may define the criteria using the Where-Object cmdlet, just as you did before.

Where-Object -FilterScript {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’}

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.Status -eq ‘Running’

But now instead of returning entire objects or even a few Properties, you’d like to return the string <ServiceName> is running for each object using the code **Write-Host -ForegroundColor ‘Yellow’ <ServiceName> “is running”.

You are now manipulating the output and creating your own string. The only way to do that is to use the ForEach-Object cmdlet as shown below. Below you can see that for each object returned via Where-Object, PowerShell runs the code Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running”.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

.DisplayName “is running” for each object returned from Where-Object, as seen below.

PS51> Get-Service -ServiceName * | Where-Object {$_.DisplayName -Like “Windows*” -and $_.Status -eq ‘Running’} | Foreach-Object { Write-Host -ForegroundColor ‘Yellow’ $_.DisplayName “is running” }

Using Where-Object to filter by propertyUsing Where-Object to filter by property

The ForEach-Object cmdlet comes in handy in a variety of situations. You could, for example, add logic to go through every service object detected and, depending on a property value, modify the color and phrasing of the output message, or even start a stopped service.

Consider the possibilities this opens up for you! You could write a script that accepts one command and runs it across several objects with a little thinking and design.

Object Comparison

You may need to compare the property values of two objects at times.

Perhaps your network has two systems that are almost similar. However, you’re having trouble with a service on one of the two systems, which you believe is a configuration problem.

You come to the Conclusion that, since these systems are located in separate sections of your network, you’ll have to utilize remote commands to collect the data in a PowerShell session. You open your preferred editor and start writing a screenplay. This script connects to two distinct servers and enumerates all processes on each of them, as seen below.

‘Svr01a.contoso.com’ = $A $B = ‘contoso.com/Svr02b’ $ProcA = Invoke-Command -Computername -Computername -Computername -Computername -Computername Get-Process -Name * $A -Scriptblock Invoke-Command -ComputerName $ProcB Get-Process -Name * $B -Scriptblock

In the $ProcA and $ProcB variables, you’ve now caught all of the processes on each machine. You must now compare them. You may go through each set of processes manually or use a cmdlet called Compare-Object to make it easier.

Compare-Object compares the property values of two distinct objects. This cmdlet reads each object’s properties, examines their values, and then returns what’s changed and what’s the same.

To utilize Compare-Object, provide each object as the parameter values for the ReferenceObject and DifferenceObject parameters, as shown below.

$ProcA -DifferenceObject $ProcB Compare-Object -ReferenceObject $ProcA

By default, Compare-Object will only return differences in the objects indicated by the SideIndicator property.  The symbols or side indicators used are >, < , & = to show the matches of objects being compared.

Using the Compare-Object commandUsing the Compare-Object command

When using Compare-Object with the switch argument IncludeEqual, you may get a list of object characteristics that are the same. If this is the case, the side indication will be ==. ExcludeDifferent may also be used to exclude differences.

Compare-Object is a really helpful cmdlet. If you’re interested in learning more, check out the online documentation.

Custom Objects in Action

It’s time to make your own objects now that you know what they are and how to operate with them.

Using Hashtables to Create Custom Objects

Using hashtables is one approach to make your own objects. Hashtables are collections of key/value pairs that are used to create attributes for objects.

Let’s begin by utilizing a hashtable to create a custom PowerShell object with some key/value pairs. You’re creating a hashtable in the example below. A single object and its characteristics are represented by this hashtable. After you’ve defined the hashtable $CarHashtable, you’ll need to utilize the PsCustomObject type accelerator.

The pscustomobject type accelerator allows you to quickly generate a pscustomobject instance. Casting is the term for this kind of activity.

You should have a pscustomobject object ($CarObject) with five properties at the Conclusion of the code line below.

## Create a hashtable. @CarHashtable $$$$$$$$ ‘Ford’ is the brand, ‘Truck’ is the style, and ‘F-150’ is the model. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new object [PsCustomObject] $CarObject = [PsCustomObject] $CarObject = [PsCustomObject] $ $CarHashTable

You may also use the New-Object cmdlet to create a new object. You could do it the long-form manner with New-Object instead of utilizing the pscustomobject type accelerator with the same hashtable. This is shown in the example below.

@CarHashtable $$$$$$$$ ‘Ford’ is the brand. ‘Truck’ as a style ‘F-150’ is the model name. ‘Red’ is the color. ‘4×4’ is the drivetrain. # Make a new item $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object -TypeName PsObject -Properties $CarObject = New-Object $CarHashtable

When $CarObject is generated, you may access each of the properties as if they came from a built-in PowerShell cmdlet like Get-Service, as seen below.

Examining the qualities of a thingExamining the qualities of a thing

Adding & Removing Properties

You may not only construct custom items, but you can also add to them. Do you remember how to use the Get-Member cmdlet? Add-Member is a relative of Get-Member. The Add-Member cmdlet adds members rather than enumerating them.

Perhaps you’d want to add a model year attribute to the previously generated custom object, as an example. You may achieve this by passing an object to Add-Member with the following parameters:

  • The sort of participant (in this case a simple NoteProperty)
  • The property’s name is (Year)
  • The property’s market worth (Value)

Here’s an example of what I’m talking about.

PS51> $CarObject | Add-Member -MemberType NoteProperty -Name ‘Year’ -Value ‘2010’

As you can see below, it looks to be identical to any other property.

Adding a new property and seeing itAdding a new property and seeing it

Many other categories of members may be added using similar procedures. Take a look at the Add-Member documentation if you want to learn more on your own.

A member may be readily removed from an object. Despite the lack of a Remove-Member cmdlet, you may still do so by using the Remove() function on the object, as illustrated below. In the following part, you’ll learn about techniques.

PS51> $CarObject.psobject.Properties.remove(‘Drivetrain’)

Methods in a Nutshell

You’ve been dealing with properties throughout this article. You’ve looked at property values, generated your own, and added and deleted properties. However, you haven’t done anything to help the environment. On the server, you haven’t made any changes. Let’s get some ways to work.

Methods are used to carry out some kind of activity. Objects hold data, while methods perform actions.

You may be familiar with the Stop-Service command, for example. This command is used to terminate a Windows service. You may do this by sending an object from Get-Service straight to Stop-Service.

Below is an example of how to disable the BITS service. This example terminates the BITS service and then verifies that it has been terminated by checking the status. With cmdlets, you’ve done two things: stopped the service and checked the status.

PS51> Get-Service -ServiceName ‘BITS’ | Stop-Service PS51> Get-Service -ServiceName ‘BITS’

Stop-Service allows you to use methods built straight into the service objects rather than calling Get-Service again and executing a separate command. There are methods on a lot of things. Stop-Service and the second Get-Service reference aren’t required in this situation.

Stopping and starting a service using commandsStopping and starting a service using commands

You may use a single object to stop and obtain the updated status by performing methods on the service object itself. This is shown in the video below. You’ll see that the Stop() and Start() functions allow you to modify the service in the same way that the commands did.

You may use the Refresh() function, which operates like another Get-Service command call, to ensure the Status property value is up to current after the service status has changed.

## On the local system, disable BITS. #Object you’re dealing with $Svc.Stop() #Method / action you’re performing $Svc.Refresh () $Svc #Method / action you’re taking #Property #Status #On the local computer, start BITS. #Object you’re dealing with $Svc.Start() #Method / action you’re taking $Svc = Get-Service -ServiceName ‘BITS’ #Method / action $Svc.Status #Property $Svc.Status #Property $Svc.Status #Property $Svc.Status #Propert

The following output should appear:

Methods on the service object are being executed.Methods on the service object are being executed.

Check out the about Methods help topic for further information about methods.

Conclusion

In PowerShell, objects may be used for a variety of purposes. This essay was just meant to serve as a starting point for you to study them. You learnt some of the fundamentals of what objects are, how to act on them, modify them, and create them in this article. You’ve seen a few distinct situations with code examples that demonstrated how to do these tasks. Maintain your composure and study PowerShell. Thank you for taking the time to read this!

The “powershell get object -property value” is a PowerShell command that allows users to retrieve the property value of an object. This command can be used on any type of object, including objects in arrays and hash tables.

Frequently Asked Questions

What are objects in PowerShell?

A: Objects in PowerShell are a type of variable. They hold values that can be accessed as they are created and destroyed by the program.

How do objects work in PowerShell?

A: Objects in PowerShell are a way to reference more than one item at the same time, and you can use them like regular variables. 。

What PowerShell command is used to discover and learn about objects?

A: The Get-Member cmdlet is used to discover and learn about objects.

Related Tags

  • powershell get properties of object
  • powershell get object property names
  • powershell object -property
  • powershell custom objects
  • powershell object types

Table of Content