Chapter 21. Part 2 — Create objects and output objects. PowerShell in depth Don Jones, Richard Siddaway
here are different ways to create objects in PowerShell. The tips and tricks. The text is too big. For all learners posic.
Except for readability, a number of key requirements for the preservation of order properties, all these methods are essentially doing the same thing. A few subtle differences in technique 1, the hash table. Usually the fastest, slower technique 2, technique 3 can be considerably slower.
In good reviews learn-powershell.net/2010/09/19/custom-powershell-objects-and-performance measured the speed of creation of objects made MVP Boe Prox. Compares the speed of three methods, work Add-Member 10 times slower. So that's a plus to the technique 1. We have not tested the technique 4 as did the Boe, but our tests show that the technique 4 faster 10% than technique 1. Technique 5 should be used in those cases where the typing properties of matter.
The translation:
21.2 Syntax for creating custom objects
We are often told that there are always multiple ways to do anything in PowerShell, and this is true for custom objects. We will show you all the basic ways, because you will surely encounter them in life, we want you to recognize them and use them whenever you want.
Chapter 21.1 Technique number 1. The use of hash tables to create custom objects.
Let's start of reception which usually we use ourselves when we want to create your own object or to combine information from different objects into one for subsequent withdrawal. We call this the official way or recommended. We use it because it makes it easy to write code that reads well, and ultimately allows you to make faster my work.
This method is demonstrated in listing 21.2 below
the
by performing this code you will get the result like this:
the
Because the output you have more than four properties PowerShell did display in the list view. You could do
the
to get a table. Please note, the fact that you create one object by combining information from four sites. You do this by creating a hash table in which prescribed the desired property names, values are property values of other objects. This is what you did in the hash table pointing:
the
If you place entries in the hash table on one line, you will need to separate each property with a semicolon. If you put each property on a separate line, you don't need a semicolon, you will much easier to read and edit code.
Brackets with presutstvuet familiar to them @ they say that then begins the hash table. Because the table is in the variable $props it is easy to pass in parameters to the property of the new object. Object PSObject is specifically provided for this purpose.
The advantage of this approach is that it is easy to build a hash table on the fly and create a lot of custom objects. You may notice that in the output object properties are not the same order as they were defined in the table. One possible solution is to create the formatting for the custom object (special XML file describing how to display, in what order, etc.) or if you use powershell 3 or higher, you can use the property ordered
the
Everything else is the same. Now the object properties are displayed in the order they were written. If you pass $obj Get-Member, you will see that it is PS-CustomObject.
note PowerShell by default does not track the order of elements in the hash table. That's why when you see the final conclusion of its properties are not in the order in which you created them. Starting with PowerShell 3, you can fix this by using the attribute [ordered]. This creates an ordered dictionary (also called hash table) and supports the order of the elements in it.
21.2.2 Technique 2. Use Select-Object
This method was a favorite in the PowerShell v1, and we still see people using it. We don't love it because it is much more difficult to read. The following listing shows the technique where we create an empty object, and then write the values of these properties
Listing 21.3. Creating an object using Select-Object
the
Please note that in listing 21.3 has been done $obj = 1, essentially a value of 1 will never be used.
COUNCIL You will see many examples where an empty string used as initializer: $obj="" | select .... It's just a way to determine $obj as an object to throw to the Assembly line something to go to Select-Object, which does all the work.
This approach has a drawback. Will provide $obj to Get-Member and look at the result.
the
Properties in place, but TypeName can cause problems or even just confusing, it all depends on what you intend to do with this object. We recommend avoiding this technique.
21.2.2 Technique 3. Use Add-Member
This method is considered formal. We believe that it illustrates what happens in life with formal approaches. It is the most expensive computationally, slower, so you don't often see people using it in real life. This is the most common approach PowerShell v1. There are two variations, the first listing with the code.
Listing 21.4. Create object using Add-Member
the
We have created a PSObject and add one property to it at a time. You need to call method each time when you add a NoteProperty which contains only a static value. To reduce the code we used positional parameters Add-Member. If you use the full syntax for each operator, Add-Member will look like the following
the
you see it turns out a lot of code.
A variation of this method lies in the use of the parameter -PassThru (abbreviated to Pass in listing 21.5) commands Add-Member. This option will put the modified object back to the pipeline so that you can pass it on to the next team and so on.
Will show you an example
Listing 21.4. Create object using Add-Member with-PassThru parameter
the
You can find this approach in life. In fact, from the point of view of operation it is a vital technique because it is much clearer what is happening. This approach should not be syntactic shortcuts and are easier to disassemble step by step.
21.2.4 Technique 4. The use of type Declaration
This is a variation of technique 1, only works in PowerShell v3 and v4, this method more compact. You start with the same hash table.
the
You could continue to fill the variable $props, the trick of this technique is that the order of the properties in the object will be stored as if we used the Directive [ordered]
Council. The type we use is a PSCustomObject. You should use this type because .NET terms you use the PSObject constructor without parameters. Do not try to shorten the code instead of putting the object PSObject PSCustomObject, you will not get the desired result.
You may have noticed that the previous methods add properties in a different order than you add them. In technique 1, for example, we have not added Computer_Name first, but it would be displayed first in the list. Don't worry, the vast majority of cases, PowerShell works with properties in any order. Technique 4 preserves the order of the properties if you need it use it.
21.2.5 Technique 5. Create a new class
A not often used technique. It gives some advantages in process on the Assembly line. Can be evaluated as an advanced technique, not all powerdensity want to delve into .NET. But the feature is available as an option
Listing 21.7 to create an object using class
the
Listing 21.7 begins with the creation of the record containing the C# code describing the class. The class has a name, MyObj and makes a number of descriptions properties of the class. In this example, properties are specified as strings, but allowed to mix types. And while we are not going to record to set the properties in the future, the class definition requires a record GET and SET, otherwise PowerShell will throw an exception.
Add-Type is used to compile the class, then we can use it instead of PSObject. To set the properties of an object can be used the technique presented here in listing 21.6:
the
let's test to Get-Member
the
This more cumbersome, but has its advantages. If you declare a property as a string and try to write down the number that will be generated error message.
21.2.6 What are the differences???
In addition to readability, a number of key requirements for the preservation of order properties, all these methods are essentially doing the same thing.
A few subtle differences in technique 1, the hash table. Typically the fastest, especially when you are working with multiple objects, tech 2 a bit slower, technique 3 can be considerably slower.
In good reviews learn-powershell.net/2010/09/19/custom-powershell-objects-and-performance measured the speed of creation of objects made MVP Boe Prox. Compares the speed of three methods, work Add-Member 10 times slower. So that's a plus to the technique 1. We have not tested the technique 4 as did the Boe, but our tests show that the technique 4 faster 10% than technique 1. Technique 5 should be used in those cases where the typing properties of matter.
Article based on information from habrahabr.ru
Except for readability, a number of key requirements for the preservation of order properties, all these methods are essentially doing the same thing. A few subtle differences in technique 1, the hash table. Usually the fastest, slower technique 2, technique 3 can be considerably slower.
In good reviews learn-powershell.net/2010/09/19/custom-powershell-objects-and-performance measured the speed of creation of objects made MVP Boe Prox. Compares the speed of three methods, work Add-Member 10 times slower. So that's a plus to the technique 1. We have not tested the technique 4 as did the Boe, but our tests show that the technique 4 faster 10% than technique 1. Technique 5 should be used in those cases where the typing properties of matter.
The translation:
21.2 Syntax for creating custom objects
We are often told that there are always multiple ways to do anything in PowerShell, and this is true for custom objects. We will show you all the basic ways, because you will surely encounter them in life, we want you to recognize them and use them whenever you want.
Chapter 21.1 Technique number 1. The use of hash tables to create custom objects.
Let's start of reception which usually we use ourselves when we want to create your own object or to combine information from different objects into one for subsequent withdrawal. We call this the official way or recommended. We use it because it makes it easy to write code that reads well, and ultimately allows you to make faster my work.
This method is demonstrated in listing 21.2 below
the
# Collect kakieto data, in the future we need to build and bring
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
# The hash table. Describes the properties of the future project
$props = @{OSVersion=$os.version
Model=$cs.model
Manufacturer=$cs.manufacturer
BIOSSerial=$bios.serialnumber
ComputerName=$os.CSName
OSArchitecture=$os.osarchitecture
ProcArchitecture=$proc.addresswidth}
# Create an object from the hash table and print
$obj = New-Object –TypeName PSObject –Property $props
Write-Output $obj
by performing this code you will get the result like this:
the
Manufacturer : Microsoft Corporation
OSVersion : 6.3.9600
OSArchitecture : 64-bit
BIOSSerial : 036685734653
ComputerName : RSSURFACEPRO2
Model : Surface Pro 2
ProcArchitecture : 64
Because the output you have more than four properties PowerShell did display in the list view. You could do
the
Write-Output $obj | ft
to get a table. Please note, the fact that you create one object by combining information from four sites. You do this by creating a hash table in which prescribed the desired property names, values are property values of other objects. This is what you did in the hash table pointing:
the
Manufacturer=$cs.manufacturer
If you place entries in the hash table on one line, you will need to separate each property with a semicolon. If you put each property on a separate line, you don't need a semicolon, you will much easier to read and edit code.
Brackets with presutstvuet familiar to them @ they say that then begins the hash table. Because the table is in the variable $props it is easy to pass in parameters to the property of the new object. Object PSObject is specifically provided for this purpose.
The advantage of this approach is that it is easy to build a hash table on the fly and create a lot of custom objects. You may notice that in the output object properties are not the same order as they were defined in the table. One possible solution is to create the formatting for the custom object (special XML file describing how to display, in what order, etc.) or if you use powershell 3 or higher, you can use the property ordered
the
$props = [ordered]@{ OSVersion=$os.version
Model=$cs.model
Manufacturer=$cs.manufacturer
BIOSSerial=$bios.serialnumber
ComputerName=$os.CSName
OSArchitecture=$os.osarchitecture
ProcArchitecture=$proc.addresswidth}
Everything else is the same. Now the object properties are displayed in the order they were written. If you pass $obj Get-Member, you will see that it is PS-CustomObject.
note PowerShell by default does not track the order of elements in the hash table. That's why when you see the final conclusion of its properties are not in the order in which you created them. Starting with PowerShell 3, you can fix this by using the attribute [ordered]. This creates an ordered dictionary (also called hash table) and supports the order of the elements in it.
21.2.2 Technique 2. Use Select-Object
This method was a favorite in the PowerShell v1, and we still see people using it. We don't love it because it is much more difficult to read. The following listing shows the technique where we create an empty object, and then write the values of these properties
Listing 21.3. Creating an object using Select-Object
the
# Our four unchanged four teams
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
# creating an object using Select-Object
$obj = 1 | Select-Object ComputerName,OSVersion,OSArchitecture, ProcArchitecture,Model,Manufacturer,BIOSSerial
# fill in the fields
$obj.ComputerName = $os.CSName
$obj.OSVersion = $os.version
$obj.OSArchitecture = $os.osarchitecture
$obj.ProcArchitecture = $proc.addresswidth
$obj.BIOSSerial = $bios.serialnumber
$obj.Model = $cs.model
$obj.Manufacturer = $cs.manufacturer
Write-Output $obj
Please note that in listing 21.3 has been done $obj = 1, essentially a value of 1 will never be used.
COUNCIL You will see many examples where an empty string used as initializer: $obj="" | select .... It's just a way to determine $obj as an object to throw to the Assembly line something to go to Select-Object, which does all the work.
This approach has a drawback. Will provide $obj to Get-Member and look at the result.
the
PS C:\> $obj | Get-Member
TypeName: Selected.System.Int32
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BIOSSerial NoteProperty System.String BIOSSerial=
ComputerName NoteProperty System.String ComputerName= WIN-KNBA0R0TM23
Manufacturer NoteProperty System.String Manufacturer= VMware, Inc.
Model NoteProperty System.String Model= VMware Virtual Platform
OSArchitecture NoteProperty System.String OSArchitecture= 64-bit
OSVersion NoteProperty System.String OSVersion= 6.1.7601
ProcArchitecture NoteProperty System.UInt16 ProcArchitecture=64
Properties in place, but TypeName can cause problems or even just confusing, it all depends on what you intend to do with this object. We recommend avoiding this technique.
insert from translator
Here we have in mind here is that:
we Get-Member the example from listing 21.2, where we created the hash table
now suppose GM example from listing 21.3 — create using Select-Object
21.2.2 Technique 3. Use Add-Member
This method is considered formal. We believe that it illustrates what happens in life with formal approaches. It is the most expensive computationally, slower, so you don't often see people using it in real life. This is the most common approach PowerShell v1. There are two variations, the first listing with the code.
Listing 21.4. Create object using Add-Member
the
# Our four unchanged four teams
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
# create an object specifying its type
$obj = New-Object –TypeName PSObject
# add a field specifying the type and value
$obj | Add-Member NoteProperty ComputerName $os.CSName
$obj | Add-Member NoteProperty OSVersion $os.version
$obj | Add-Member NoteProperty OSArchitecture $os.osarchitecture
$obj | Add-Member NoteProperty ProcArchitecture $proc.addresswidth
$obj | Add-Member NoteProperty BIOSSerial $bios.serialnumber
$obj | Add-Member NoteProperty Model $cs.model
$obj | Add-Member NoteProperty Manufacturer $cs.manufacturer
We have created a PSObject and add one property to it at a time. You need to call method each time when you add a NoteProperty which contains only a static value. To reduce the code we used positional parameters Add-Member. If you use the full syntax for each operator, Add-Member will look like the following
the
Add-Member -MemberType NoteProperty -Name ComputerName -Value $os.CSName
you see it turns out a lot of code.
A variation of this method lies in the use of the parameter -PassThru (abbreviated to Pass in listing 21.5) commands Add-Member. This option will put the modified object back to the pipeline so that you can pass it on to the next team and so on.
Will show you an example
Listing 21.4. Create object using Add-Member with-PassThru parameter
the
# Our four unchanged four teams
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
# create an object specifying its type
$obj = New-Object –TypeName PSObject
# create properties
$obj | Add-Member NoteProperty ComputerName $os.CSName –pass |
Add-Member NoteProperty OSVersion $os.version –pass |
Add-Member NoteProperty OSArchitecture $os.osarchitecture –Pass |
Add-Member NoteProperty ProcArchitecture $proc.addresswidth –pass |
Add-Member NoteProperty BIOSSerial $bios.serialnumber –pass |
Add-Member NoteProperty Model $cs.model –pass |
Add-Member NoteProperty Manufacturer $cs.manufacturer
Write-Output $obj
You can find this approach in life. In fact, from the point of view of operation it is a vital technique because it is much clearer what is happening. This approach should not be syntactic shortcuts and are easier to disassemble step by step.
insert translator
meant that debugging easier
21.2.4 Technique 4. The use of type Declaration
This is a variation of technique 1, only works in PowerShell v3 and v4, this method more compact. You start with the same hash table.
the
# Our four unchanged four teams
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
$obj = [pscustomobject]@{
OSVersion=$os.version
Model=$cs.model
Manufacturer=$cs.manufacturer
BIOSSerial=$bios.serialnumber
ComputerName=$os.CSName
OSArchitecture=$os.osarchitecture
ProcArchitecture=$proc.addresswidth
}
Write-Output $obj
You could continue to fill the variable $props, the trick of this technique is that the order of the properties in the object will be stored as if we used the Directive [ordered]
Council. The type we use is a PSCustomObject. You should use this type because .NET terms you use the PSObject constructor without parameters. Do not try to shorten the code instead of putting the object PSObject PSCustomObject, you will not get the desired result.
You may have noticed that the previous methods add properties in a different order than you add them. In technique 1, for example, we have not added Computer_Name first, but it would be displayed first in the list. Don't worry, the vast majority of cases, PowerShell works with properties in any order. Technique 4 preserves the order of the properties if you need it use it.
21.2.5 Technique 5. Create a new class
A not often used technique. It gives some advantages in process on the Assembly line. Can be evaluated as an advanced technique, not all powerdensity want to delve into .NET. But the feature is available as an option
Listing 21.7 to create an object using class
the
$source=@"
public class MyObject
{
public string ComputerName {get; set;}
public string Model {get; set;}
public string Manufacturer {get; set;}
public string BIOSSerial {get; set;}
public string OSArchitecture {get; set;}
public string OSVersion {get; set;}
public string ProcArchitecture {get; set;}
}
"@
Add-Type -TypeDefinition $source -Language CSharpversion3
# our four teams
$os = Get-WmiObject –Class Win32_OperatingSystem –comp localhost
$cs = Get-WmiObject –Class Win32_ComputerSystem –comp localhost
$bios = Get-WmiObject –Class Win32_BIOS –comp localhost
$proc = Get-WmiObject –Class Win32_Processor –comp localhost | Select –First 1
$props = @{OSVersion=$os.version
Model=$cs.model
Manufacturer=$cs.manufacturer
BIOSSerial=$bios.serialnumber
OSArchitecture=$os.osarchitecture
ProcArchitecture=$proc.addresswidth}
$obj = New-Object –TypeName MyObject –Property $props
Write-Output $obj
Listing 21.7 begins with the creation of the record containing the C# code describing the class. The class has a name, MyObj and makes a number of descriptions properties of the class. In this example, properties are specified as strings, but allowed to mix types. And while we are not going to record to set the properties in the future, the class definition requires a record GET and SET, otherwise PowerShell will throw an exception.
Add-Type is used to compile the class, then we can use it instead of PSObject. To set the properties of an object can be used the technique presented here in listing 21.6:
the
$obj = [MyObject]@{OSVersion=$os.version
Model=$cs.model
Manufacturer=$cs.manufacturer
BIOSSerial=$bios.serialnumber
ComputerName=$os.CSName
OSArchitecture=$os.osarchitecture
ProcArchitecture=$proc.addresswidth
}
let's test to Get-Member
the
PS C:\> $obj | get-member
TypeName: MyObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BIOSSerial Property string BIOSSerial {get;set;}
ComputerName Property string ComputerName {get;set;}
Manufacturer Property string Manufacturer {get;set;}
Model Property string Model {get;set;}
Property string OSArchitecture OSArchitecture {get;set;}
Property string OSVersion OSVersion {get;set;}
ProcArchitecture ProcArchitecture string Property {get;set;}
This more cumbersome, but has its advantages. If you declare a property as a string and try to write down the number that will be generated error message.
21.2.6 What are the differences???
In addition to readability, a number of key requirements for the preservation of order properties, all these methods are essentially doing the same thing.
A few subtle differences in technique 1, the hash table. Typically the fastest, especially when you are working with multiple objects, tech 2 a bit slower, technique 3 can be considerably slower.
In good reviews learn-powershell.net/2010/09/19/custom-powershell-objects-and-performance measured the speed of creation of objects made MVP Boe Prox. Compares the speed of three methods, work Add-Member 10 times slower. So that's a plus to the technique 1. We have not tested the technique 4 as did the Boe, but our tests show that the technique 4 faster 10% than technique 1. Technique 5 should be used in those cases where the typing properties of matter.
Комментарии
Отправить комментарий