I'm a newbie of powershell, I'm starting right now to look at objects, etc.
I'm creating an object in this way:
$myObject = [PSCustomObject]#{
ComputerName = "abc"
Data = "xxx"
}
If I then print $myObject what i get is:
ComputerName Data
------------ ----
abc xxx
And everything is ok, now I want to add a property to that object, and I saw (tell me if i'm wrong) that I can do it in 2 ways: with add-member and with select-object
For example with add-member what I did was:
$myObject | Add-member -NotePropertyName Level -NotePropertyValue Highest
Instead with Select-object I did:
$myobject = 2 (cause i want to add 2 properties, is it right?) | Select-Object -Property Level, Privilege
$myobject.Level = "High"
$myobject.Privilege = "Elevated"
Now if I run $myobject I still only get:
ComputerName Data
------------ ----
abc xxx
What should I do to see all the data, even the one that I added later?
Can I directly add the values to the properties added through Select-Object?
Thanks
You can use the Add-Member method on a PsCustomObject.
$myObject = [PSCustomObject]#{
ComputerName = "abc"
Data = "xxx"
}
$myObject | Add-Member -NotePropertyName Level -NotePropertyValue High
$myObject | Add-Member Privilege Elevated
$myObject
#Output looks like,
ComputerName Data Level Privilege
------------ ---- ----- ---------
abc xxx High Elevated
Update
Not sure at the moment why but will elaborate on it ...
If you print the Pscustomobject and then run the add-member, they seem to be ignored. If you create a hashtable, update it and then convert to PsObject, it works. Following is an example of that hashtable
$myObject = #{
ComputerName = "abc"
Data = "xxx"
}
$myObject | ft
$myObject.Add("Level", "high")
$myObject.Add("Privilege", "Elevated")
[pscustomobject] $myObject | ft
What I found
When you print $myObject then add the data, the data is added but not displayed. This is due to some internal mechanism, unknown to me, that continues to use the same headers from previous command.
If you notice, the data is printed twice under the same heading. If you want to see the differences before and after, pipe it to format-list or format-table to use a different output stream each time.
$myObject = [PSCustomObject]#{
ComputerName = "abc"
Data = "xxx"
}
$myObject | ft
$myObject | Add-Member -NotePropertyName Level -NotePropertyValue High -Force
$myObject | Add-Member Privilege Elevated
$myObject | ft
You can use either Add-Member or Select-Object. Withstanding the advantages or disadvantages in different situations I just want to throw in the Select-Object example. Just so you have both methods:
This example will echo the object with the selected properties:
$myObject |
Select-Object *,
#{Name = 'Level'; Expression = { 'High' } },
#{Name = 'Privilege'; Expression = { 'Elevated' } }
If you want to save the new properties back to the object variable you'll have to reassign like below:
$myObject = $myObject |
Select-Object *,
#{Name = 'Level'; Expression = { 'High' } },
#{Name = 'Privilege'; Expression = { 'Elevated' } }
PowerShell allows you to provide a hash table to define the new properties. You'll note it looks fairly similar to the hash you used to create the object. Typically the expression would leverage the $_ syntax to calculate the property's value. You will often here these referred to as calculated properties.
Related
I am trying to parse parameters of a Graph command to get every value and attribute name. The reason would be to use Compare-Object between the current state of an object and bodyparams added as JSON or an array in Powershell.
Or even create a simple function to compare any of the old params with the JSON for any change, and create a parms with the differences.
The conceptual idea would be to have a template for any modification without using the commands, the old object's params, to compare with a new set of params from the diff.
So far, I managed to do this :
Get-MgGroup -GroupId $GroupId | Select-Object * |Convertto-Json
Which returns :
{
"AcceptedSenders": null,
"AllowExternalSenders": null,
"AppRoleAssignments": null,
"AssignedLabels": null,
"AssignedLicenses": null,
(The whole JSON is too long to be put here, and it would be pointless. It's just attributes and objects)
Which is what I'd want. But I would want to do the same with the object itself
Definition is where the values are since this command:
Get-MgGroup -GroupId $GroupId | Select-Object * | Get-Member -MemberType NoteProperty
Returns this :
Name MemberType Definition
---- ---------- ----------
AcceptedSenders NoteProperty object AcceptedSenders=null
AdditionalProperties NoteProperty Dictionary[string,Object] AdditionalProperties=System.Collections.Generic.Dictionary`2[System.String,System.Object]
AllowExternalSenders NoteProperty object AllowExternalSenders=null
AppRoleAssignments NoteProperty object AppRoleAssignments=null
AssignedLabels NoteProperty object AssignedLabels=null
AssignedLicenses NoteProperty object AssignedLicenses=null
AutoSubscribeNewMembers NoteProperty object AutoSubscribeNewMembers=null
Calendar NoteProperty MicrosoftGraphCalendar Calendar=Microsoft.Graph.PowerShell.Models.MicrosoftGraphCalendar
CalendarView NoteProperty object CalendarView=null
Classification NoteProperty object Classification=null
Conversations NoteProperty object Conversations=null
CreatedDateTime NoteProperty datetime CreatedDateTime=04/09/2022 05:48:57
CreatedOnBehalfOf NoteProperty MicrosoftGraphDirectoryObject CreatedOnBehalfOf=Microsoft.Graph.PowerShell.Models.MicrosoftGraphDirectoryObject
DeletedDateTime NoteProperty objec
As you can see, not every value is null or a string, so I cannot just fill an empty object with an iteration of the name with null on it.
In simple terms, I would like to get from the cmd's any "NoteProperty" : the name, the type, and the value.
I figure it might be hard to grasp without context, I wrote a draft on kroki
enter image description here
The idea would have a model for any future change, but I wouldn't want to change it manually every time.
Edit :
I actuall went further and maybe that'll be more evident with the function :
function Compare-Attributes {
Get-MgGroup -GroupId $GroupId | Select-Object -Property * | ConvertTo-Json -Compress | Out-file -FilePath 'C:\Users\Currentusr\Currentdir\BodyParams.JSON'
### I change some values
$old_parms = #(Get-MgGroup -GroupId $GroupId | Select-Object -Property * | ConvertTo-Json )
$new_parms = #(Get-Content 'C:\Users\Currentusr\Currentdir\BodyParams.JSON' | Convertfrom-Json )
$new_parms = #(Get-Content 'C:\Users\YassinBousaadi\projects\Ansible\Ansible_Modules\BodyParams.JSON' | Convertfrom-Json |
Edit-LeafProperty -PassThru { if ($null -eq $_.Value) { $_.Value = 'null' } } | ConvertTo-Json)
$old_parms_obj = #( $old_parms| ConvertFrom-Json)
$new_parms_obj = #( $new_parms | ConvertFrom-Json)
echo $new_parms_obj
Compare-Object -ReferenceObject $old_parms_obj `
-DifferenceObject $new_parms_obj `
-IncludeEqual `
What it returns is actually not half bad :
InputObject
-----------
#{AcceptedSenders=null; AllowExternalSenders=null; AppRoleAssignments=null; AssignedLabels=null; AssignedLicenses=null; AutoSubscribeNewMembers=null; Calendar=; CalendarView=null; Classification=null; Conversations=null; CreatedDateTime=04/09/2022 05:48:57; CreatedOnB...
I changed the AcceptedSenders attribute as true in the JSON in between, so that value should show. but that'll be the one to show, since it's the only one that's changed, right ? I even went and changed every null value to actual null as strings in the JSON because it would otherwise return empty values
I got an $Object with a ton of properties which look like this:
IsSynchronized : { False, False }
What I want is to do something like :
$Object | Export-Csv C:\Test\Merge.csv -Delimiter ';'
To get a CSV containing :
IsSynchronized
--------------
False
False
But as expected I get
IsSynchronized
---------------
System.Object[]
Is there a good way to get a ton of the object's properties in a .CSV ?
I have 6 .csv files with values and I try to add them in to one big .csv for further processing.
Edit:
I asked about this Topic yesterday but i need to make more clear what i want.
I create a PSCustomObject and fill it with Arrays:
$Object = New-Object -TypeName PSCustomObject
$Object | add-member -membertype NoteProperty -name "CPUHost" -value $global:CPUHost
$Object | add-member -membertype NoteProperty -name "NumCpu" -value $global:NumCpu
$Object | add-member -membertype NoteProperty -name "MemoryMB" -value $global:MemoryMB
$Object | add-member -membertype NoteProperty -name "CPU Usage (Average), Mhz" -value $global:CPUUsageAverageMhz
$Object | add-member -membertype NoteProperty -name "CPU Usage (Average), %" -value $global:CPUUsageAverage
$Object | add-member -membertype NoteProperty -name "Memory Usage (Average), %" -value $global:MemoryUsageAverage
$Object | add-member -membertype NoteProperty -name "Network Usage (Average), KBps" -value $global:NetworkUsageAverageKBps
$Object | add-member -membertype NoteProperty -name "Disk Usage (Average), KBps" -value $global:DiskUsageAverageKBps
...
All of these Global Variables are Arrays because i never know how many Values i get in the first place.
They are filled by lopping through 6 CSV Files i will allways get.
After running this bit i will have a Object looking like this:
CPUHost : {xxxx}
NumCpu : {20}
MemoryMB : {36094}
CPU Usage (Average), Mhz : {3914,33}
CPU Usage (Average), % : {8,91}
Memory Usage (Average), % : {70,17}
Network Usage (Average), KBps : {439,68}
Disk Usage (Average), KBps : {1994,93}
...
What i want is to Export that in to a CSV Displayed like :
CPUHost NumCPU MemoryMb CPUUsage ...
------- ------ -------- ---------
xxxx 20 36094 3914
33
With every Value in its own Cell.
What i get is instead of the values : System.Type.[] which is technically correct but not what i need.
I allready tryed to -join the values but that will leave me with the values in the same cell
You state that you have one object with multiple properties like what was posted. I assume you have an object that looks like the following:
IsSynchronized Property2 Property3
-------------- --------- ---------
{False, False} {1, 2, 3} {string1, string2, string3, string4}
You could do the following:
$loopmax = $object[0].psobject.properties |% {($_.Value | measure-object).Count} | Sort -desc | Select -First 1
$newobject = for ($i = 0; $i -lt $loopmax; $i++) {
$hash = [ordered]#{}
foreach ($p in $object[0].psobject.properties.name) {
$hash[$p] = $object.$p[$i]
}
[pscustomobject]$hash
}
$newobject | convertto-csv -notype
This doesn't seem wise to do. CSV isn't very good for representing or storing rich or hierarchical objects. The problem is even worse when the property is an object, in your case it's a flat array. You can output as you suggest / request, and other answers have demonstrated:
IsSynchronized
--------------
False
False
However, this disrupts the property's relationship to the other properties. If you have other types like [String] & [Int], or even varying numbers of elements in array typed properties things are going to get weird quickly!
If you must stick with CSV you can sub-delimit the field. A great example of this is Exchange Message Tracking logs. They are CSV files delimited on the typical ",", but the recipients field is sub-delimited on a ";".
An example in code might look something like this:
$Object =
[PSCustomObject]#{
Prop1 = "one"
Prop2 = "two"
Arr1 = #( 1,2,3,4 )
}
$Object |
Select-Object Prop1, Prop2,
#{ Name = 'Arr1'; Expression = {$_.Arr1 -join "," } } |
ConvertTo-Csv -Delimiter ";"
Results:
"Prop1";"Prop2";"Arr1"
"one";"two";"1,2,3,4"
Note: To use full fidelity data in a later process would require appropriate handling on input. However, if you follow other solutions and said weirdness occurs you'll be left with a similar issue; having to handle on the input side everywhere you intend to use that data.
Given CSV's shortcomings JSON may be a better choice to store & reuse full fidelity objects. Export/Import CliXML are interesting for this.
To answer the literal question asked (although I'm not sure that's what the OP actually wants)...
If you have a single object with a property that contains an array of values, you can expand them out into a new array and then convert that to csv as follows:
$obj = new-object psobject -Property #{
"IsSynchronized" = #( $false, $false )
}
$obj
# IsSynchronized
# --------------
# {False, False}
$data = $obj.IsSynchronized | foreach-object {
new-object pscustomobject -Property #{ "IsSynchronized" = $_ }
}
$csv = $data | ConvertTo-Csv -NoTypeInformation
$csv
# "IsSynchronized"
# "False"
# "False"
I have a custom object that contains device information that looks something like this.
name,model,sn
PC1,Elitebook 850, ABC123,
PC2,EliteDesk 600,123ABC
I have a function that retrieves threats detected by an antivirus product. These are returned as an array of objects. There are more properties than below but this is just an example
file,md5
bad.exe,adfdfdfd
evil.exe,fdfdffdf
I would like to add each member as properties to the custom object so the final output is similar to this.
name,model,sn,01_file,01_md5,02_file,02_md5
Currently, my script does this:
foreach($device in $devices){
$threats = Get-Threats $device
[pscustomobject] #{
name = $device.device_name
make = $device.make
sn = $device.sn
ThreatFileName = $threats.File -join ", "
Threat_md5 = $threats.md5 -join ", "
}
}
This works ok but I'd really like each object returned by the 'Get-Threats' function to be listed as its own set of properties. I need this to be generated dynamically because I don't know how many threats will be returned for each device.
Any thoughts on how to go about this?
You can add properties to objects at any time with the Add-Member cmdlet. Maybe start with an empty object and loop through the elements returned by Get-Threats, adding a member each time?
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-member?view=powershell-6
Edit: Example code to answer for reference.
$o = [pscustomobject]#{
MemberA='aaa'
MemberB='bbb'
MemberC='ccc'
MemberD='ddd'
}
"Before"
$o | ft
$o | Add-Member -MemberType NoteProperty -Name 'MemberE' -Value 'eee'
$o | Add-Member -MemberType NoteProperty -Name 'MemberF' -Value 'fff'
"After"
$o | ft
The answer from #krome got me pointed in the right direction although that answer wouldn't work for me as there could be multiple threats for each device.
I used the answer from #scobi on Dynamically get PSCustomObject property and values to arrive at this answer which meets my requirement that the new properties be generated dynamically.
foreach($device in $devices){
$threats = Get-Threats $device
if($null -ne $threats){
$i = 1
foreach($threat in $threats){
$threat | Get-Member -MemberType NoteProperty | % Name | %{
Add-Member -InputObject $device -NotePropertyName ("Threat"+$i.ToString() + "_" + $_) -NotePropertyValue $threat.$_ -Force
}
$i++
}
}
}
Write-Output $devices
I loop over each device in the devices array and call my
Get-Threats function.
The if statement prevents the loop from running for any devices
that don't have threats.
$i is used as my counter to increment the property name for each
threat found so the properties will all have unique names
I then loop over each threat found piping to Get-Member to retrieve
the property name and values
I use Add-Member to add additional properties for each threat found
to each device in the loop, using the counter to give each propery a unique name
How can I change the column ordering of the output my code produces:
$apps = Import-CSV apps.csv
$computers = Import-CSV compobj.csv
foreach ($computer in $computers) {
$computerLob = $computer.lob
$lobApps = $apps | ? {$_.lob -eq $computerLob }
foreach ($app in $lobApps) {
$computerHostname = $computer.hostname
$appLocation = $app.location
$installed=Test-Path "\\$computerHostname\$appLocation"
New-Object PSObject -Property #{
Computer=$computer.hostname
App=$app.appname
Installed=$installed
}
}
Currently it's producing the columns in the following order: Installed,App,Computer.
I'd like to have it in the following order: Computer,App,Installed.
Powershell V3 added a type accelerator for [PSCustomObject] that creates objects using an ordered hash table, so the properties stay in the order they're declared:
[PSCustomObject] #{
Computer=$computer.hostname
App=$app.appname
Installed=$installed
}
If you want to ensure the output of an object occurs in a certain order i.e. formatted a certain way then use PowerShell's formatting commands.
$obj = [pscustomobject]#{Computer=$computer.hostname;App=$app.appname;Installed=$installed}
$obj | Format-Table Computer,App,Installed
What's more you can better control the output e.g.:
$obj | Format-Table Computer,App,Installed -AutoSize
Or control field width & alignment:
$obj | Format-Table #{label='Computer';expression={$_.Computer};width=20;alignment='right'},App,Installed
Frankly I think it is a better practice to use the formatting commands to get the output order you want rather than to rely upon the order in which the properties are created.
The problem is that you're adding the properties using a hashtable, and hashtables don't preserve order. You can do one of two things:
1. Add the properties in a manner that will set the order (the last line is to output the object to the pipeline):
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $computer.hostname
$obj | Add-Member -MemberType NoteProperty -Name App -Value $app.appname
$obj | Add-Member -MemberType NoteProperty -Name Installed -Value $installed
$obj
2. Determine the order at the time you output the object to the pipeline using Select-Object:
New-Object PSObject -Property #{
Computer=$computer.hostname
App=$app.appname
Installed=$installed
} | select Computer,App,Installed
Which one is preferable depends on how much you'll be working with the object. If, as your question implies, you're only using the PSObject in order to display the information in tabular format, the second method is quicker. If you're going to output the object multiple times in different parts of the script, the first method allows you to simply output it as $obj rather than having to pipe to select every time.
Note also that the second method can be split up like this if you don't want to output the object immediately after populating it:
$obj = New-Object PSObject -Property #{
Computer=$computer.hostname
App=$app.appname
Installed=$installed
}
[...do other stuff...]
$obj | select Computer,App,Installed
Format-Table it's a good solution when you need to display your object fields in a specific order, but it will change the obect and you won't be able to pipe your object, for example when exporting to csv (Export-Csv).
In the case you just want to change "the order of the fields in the object" use Select-Object. This will preserve object type and fields, and still you will be able to pipe the object to other cmdlets.
A more universal way to change the order is using the Select-Object cmdlet with the list of properties in the required order.
See the example:
PS> $ObjectList = 1..3 |
% {New-Object psobject -Property #{P2="Object $_ property P2"; P1="Object $_ property P1"}}
PS> $ObjectList
P2 P1
-- --
Object 1 property P2 Object 1 property P1
Object 2 property P2 Object 2 property P1
Object 3 property P2 Object 3 property P1
PS> $ObjectList | Select-Object P1,P2
P1 P2
-- --
Object 1 property P1 Object 1 property P2
Object 2 property P1 Object 2 property P2
Object 3 property P1 Object 3 property P2
The full form of these commands is the following:
$ObjectList = 1..3 |
ForEach-Object -Process {New-Object -TypeName psobject -Property #{P2="Object $_ property P2"; P1="Object $_ property P1"}}
$ObjectList | Select-Object -Property P1,P2
Can anybody explain the details? If I create an object using
$var = [PSObject]#{a=1;b=2;c=3}
and then I look for its type using getType() PowerShell tells me it's of type Hashtable.
When using Get-Member (alias gm) to inspect the object it's obvious that a hashtable has been created, since it has a keys and a values property. So what's the difference to a "normal" hashtable?
Also, what's the advantage of using a PSCustomObject? When creating one using something like this
$var = [PSCustomObject]#{a=1;b=2;c=3}
the only visible difference to me is the different datatype of PSCustomObject. Also instead of keys and value properties, a inspection with gm shows that now every key has been added as a NoteProperty object.
But what advantages do I have? I'm able to access my values by using its keys, just like in the hashtable. I can store more than simple key-value pairs (key-object pairs for example) in the PSCustomObject, JUST as in the hashtable. So what's the advantage? Are there any important differences?
One scenario where [PSCustomObject] is used instead of HashTable is when you need a collection of them. The following is to illustrate the difference in how they are handled:
$Hash = 1..10 | %{ #{Name="Object $_" ; Index=$_ ; Squared = $_*$_} }
$Custom = 1..10 | %{[PSCustomObject] #{Name="Object $_" ; Index=$_ ; Squared = $_*$_} }
$Hash | Format-Table -AutoSize
$Custom | Format-Table -AutoSize
$Hash | Export-Csv .\Hash.csv -NoTypeInformation
$Custom | Export-Csv .\CustomObject.csv -NoTypeInformation
Format-Table will result in the following for $Hash:
Name Value
---- -----
Name Object 1
Squared 1
Index 1
Name Object 2
Squared 4
Index 2
Name Object 3
Squared 9
...
And the following for $CustomObject:
Name Index Squared
---- ----- -------
Object 1 1 1
Object 2 2 4
Object 3 3 9
Object 4 4 16
Object 5 5 25
...
The same thing happens with Export-Csv, thus the reason to use [PSCustomObject] instead of just plain HashTable.
Say I want to create a folder. If I use a PSObject you can tell it is wrong by
looking at it
PS > [PSObject] #{Path='foo'; Type='directory'}
Name Value
---- -----
Path foo
Type directory
However the PSCustomObject looks correct
PS > [PSCustomObject] #{Path='foo'; Type='directory'}
Path Type
---- ----
foo directory
I can then pipe the object
[PSCustomObject] #{Path='foo'; Type='directory'} | New-Item
From the PSObject documentation:
Wraps an object providing alternate views of the available members and ways to extend them. Members can be methods, properties, parameterized properties, etc.
In other words, a PSObject is an object that you can add methods and properties to after you've created it.
From the "About Hash Tables" documentation:
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs.
...
Hash tables are frequently used because they are very efficient for finding and retrieving data.
You can use a PSObject like a Hashtable because PowerShell allows you to add properties to PSObjects, but you shouldn't do this because you'll lose access to Hashtable specific functionality, such as the Keys and Values properties. Also, there may be performance costs and additional memory usage.
The PowerShell documentation has the following information about PSCustomObject:
Serves as a placeholder BaseObject when PSObject's constructor with no parameters is used.
This was unclear to me, but a post on a PowerShell forum from the co-author of a number of PowerShell books seems more clear:
[PSCustomObject] is a type accelerator. It constructs a PSObject, but does so in a way that results in hash table keys becoming properties. PSCustomObject isn't an object type per se – it's a process shortcut. ... PSCustomObject is a placeholder that's used when PSObject is called with no constructor parameters.
Regarding your code, #{a=1;b=2;c=3} is a Hashtable. [PSObject]#{a=1;b=2;c=3} doesn't convert the Hashtable to a PSObject or generate an error. The object remains a Hashtable. However, [PSCustomObject]#{a=1;b=2;c=3} converts the Hashtable into a PSObject. I wasn't able to find documentation stating why this happens.
If you want to convert a Hashtable into an object in order to use its keys as property names you can use one of the following lines of code:
[PSCustomObject]#{a=1;b=2;c=3}
# OR
New-Object PSObject -Property #{a=1;b=2;c=3}
# NOTE: Both have the type PSCustomObject
If you want to convert a number of Hashtables into an object where their keys are property names you can use the following code:
#{name='a';num=1},#{name='b';num=2} |
% { [PSCustomObject]$_ }
# OR
#{name='a';num=1},#{name='b';num=2} |
% { New-Object PSObject -Property $_ }
<#
Outputs:
name num
---- ---
a 1
b 2
#>
Finding documentation regarding NoteProperty was difficult. In the Add-Member documentation, there isn't any -MemberType that makes sense for adding object properties other than NoteProperty. The Windows PowerShell Cookbook (3rd Edition) defined the Noteproperty Membertype as:
A property defined by the initial value you provide
Lee, H. (2013). Windows PowerShell Cookbook. O'Reilly Media, Inc. p. 895.
One advantage I think for PSObject is that you can create custom methods with it.
For example,
$o = New-Object PSObject -Property #{
"value"=9
}
Add-Member -MemberType ScriptMethod -Name "Sqrt" -Value {
echo "the square root of $($this.value) is $([Math]::Round([Math]::Sqrt($this.value),2))"
} -inputObject $o
$o.Sqrt()
You can use this to control the sorting order of the PSObject properties (see PSObject sorting)
I think the biggest difference you'll see is the performance. Have a look at this blog post:
Combining Objects Efficiently – Use a Hash Table to Index a Collection of Objects
The author ran the following code:
$numberofobjects = 1000
$objects = (0..$numberofobjects) |% {
New-Object psobject -Property #{'Name'="object$_";'Path'="Path$_"}
}
$lookupobjects = (0..$numberofobjects) | % {
New-Object psobject -Property #{'Path'="Path$_";'Share'="Share$_"}
}
$method1 = {
foreach ($object in $objects) {
$object | Add-Member NoteProperty -Name Share -Value ($lookupobjects | ?{$_.Path -eq $object.Path} | select -First 1 -ExpandProperty share)
}
}
Measure-Command $method1 | select totalseconds
$objects = (0..$numberofobjects) | % {
New-Object psobject -Property #{'Name'="object$_";'Path'="Path$_"}
}
$lookupobjects = (0..$numberofobjects) | % {
New-Object psobject -Property #{'Path'="Path$_";'Share'="Share$_"}
}
$method2 = {
$hash = #{}
foreach ($obj in $lookupobjects) {
$hash.($obj.Path) = $obj.share
}
foreach ($object in $objects) {
$object |Add-Member NoteProperty -Name Share -Value ($hash.($object.path)).share
}
}
Measure-Command $method2 | select totalseconds
Blog author's output:
TotalSeconds
------------
167.8825285
0.7459279
His comment regarding the code results is:
You can see the difference in speed when you put it all together. The object method takes 167 seconds on my computer while the hash table method will take under a second to build the hash table and then do the lookup.
Here are some of the other, more-subtle benefits:
Custom objects default display in PowerShell 3.0
We have a bunch of templates in our Windows-PKI and we needed a script, that has to work with all active templates. We do not need to dynamically add templates or remove them.
What for me works perfect (since it is also so "natural" to read) is the following:
$templates = #(
[PSCustomObject]#{Name = 'template1'; Oid = '1.1.1.1.1'}
[PSCustomObject]#{Name = 'template2'; Oid = '2.2.2.2.2'}
[PSCustomObject]#{Name = 'template3'; Oid = '3.3.3.3.3'}
[PSCustomObject]#{Name = 'template4'; Oid = '4.4.4.4.4'}
[PSCustomObject]#{Name = 'template5'; Oid = '5.5.5.5.5'}
)
foreach ($template in $templates)
{
Write-Output $template.Name $template.Oid
}
Type-1: $PSCustomObject = [PSCustomObject] #{a=1;b=2;c=3;d=4;e=5;f=6}
Type-2: $PsObject = New-Object -TypeName PSObject -Property #{a=1;b=2;c=3;d=4;e=5;f=6}
The only difference between Type-1 & Type-2
Type-1 Property are displayed in same order as we added
Type-1 enumerates the data faster
Type-1 will not work with systems running PSv2.0 or earlier
Both Type-1 & Type-2 are of type “System.Management.Automation.PSCustomObject”
Difference between HashTable and PSCustomObject/PSObject is
You can add new methods and properties to PSCustomObject/PSObject
You can use PSCustomObject/PSObject for pipeline parameter binding using ValueFromPipelineByPropertyName as explained by Zombo
example: [PSCustomObject] #{Path='foo'; Type='directory'} | New-Item