Updating a custom object multiple times in a script

I want to know the best way to update a custom object properties multiples times is a script. Since using += to keep adding to an array is more memory intensive operation, what is the other way which is more efficient:

I am updating the properties of my hashtable multiples times in a script based on if condition and try and catch blocks.However I do not want to use += approach, what could be the alternative best approach.

$myobject=@()
$hash=@{}
$hash.computername=$obj.computername
$hash.servicename=$obj.servicename
$hash.stauts=$status
$hash.comment="service is disabled"
$obj = New-Object -TypeName PSObject -Property $hash
$myobject+=$obj

Sam,

when you post code or error messages or sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE”, in the “Visual” view you can use the format template “Preformatted”. You can go back edit your post and fix the formatting - you don’t have to create a new one.
Thanks in advance.

You should show the rest of the code or at least the relevant part of it. If you use loops to update your custom object you could use a variable assignement in front of that loop to catch everything what “comes out”. :wink:

Thanks I have done that, yes I know I can assign a variable to a loop. However inside the loop, I have multiple if, else conditions and try and catch blocks and inside each block the properties like status and comments of my hashtable change. Inside each of these the properties of my object is changing, hence I want to achieve this without using +=

I still cannot follow. Could you show an example? … a little more than you showed above …

For example the below code. In this the servicename,status and comments will change under each block, I want to be able to change the properties of this hastable or customobject multiples times in a script without having to use +=

 

$myobject=@()
foreach($obj in $coll)
{
  try {
          mycommand -EA Stop
             $hash=@{}
             $hash.computername=$obj.computername
             $hash.servicename=$obj.servicename
             $hash.stauts=$status
             $hash.comment="service is disabled"
             $obj = New-Object -TypeName PSObject -Property $hash
             $myobject+=$obj
       }
   catch{
             $hash=@{}
             $hash.computername=$obj.computername
             $hash.servicename='N/A'
             $hash.stauts='N/A'
             $hash.comment="Error encountered"
             $obj = New-Object -TypeName PSObject -Property $hash
             $myobject+=$obj
        }
}

I’d recommned to do it this way:

$template = @{
    computername = $null
    servicename  = 'N/A'
    stauts       = 'N/A'
    comment      = 'Error encountered'
}

$Result = foreach ($obj in $coll) {
    $hashTable = $template.Clone()
    $hashTable.ComputerName = $obj.computername
    try {
        mycommand -EA Stop
        $hashTable.serviceName = $obj.servicename
        $hashTable.status = $status
        $hashTable.comment = "service is disabled"
        [PSCustomObject]$hashTable
    }
    catch {
        "I think it does not need a catch in this case ;-)"
    }
}
$result

I just gave this as an example, I need to update the properties like servicename,status and comments multiple times in my script, like between multiple if, else blocks and multiple try, catch blocks within the if, else blocks. I do not want to mention inside the catch block that it does not need a catch. This is just a sample code, if in case I need to have a update these properties inside the catch block or other blocks, what is the most efficient way to do so.

That’s what I still dont understand. I does not make any sense to update one property more than once. What counts is value it has when you use this value? Or did I get this wrong again? :wink:

The way I showed is most efficient way I know of. But maybe someone else has a more efficient way … you might wait a little longer for more answers. :wink:

I’m not sure I follow either. If you’re updating a hash table property, just assign it like

$hashtable[$element].property = "value"

By using += in your discussion, it makes me think you want to add more properties? If so you can add more to a hashtable like so

$hashtable.add('Key',"value")

Now if you’re simply just trying to make a list, by adding elements one at a time, this has nothing to do with a hash table. The below methods work the same on a regular variable as a hashtable property. Please note, system.collections.arraylist is deprecated, I’m just not comfortable enough with the generic lists to provide an example.

$variable = new-object system.collections.arraylist

[void]$variable.add("some object, string, int, etc")

 

$hashtable[$element].property = new-object system.collections.arraylist

[void]$hashtable[$element].property.add("some object, string, int, etc")

The void is just to suppress the arraylist add method output of the entry’s index. You could do | out-null as well as other methods instead.

$sName = 'WSearch', 'BadName'
foreach ($sn in $sName) {
    try {
        $service = Get-Service -Name $sn -ErrorAction Stop

        if ($service.Status -eq 'Running') {
            $comment = '{0} is running' -f $service.Name
        }
        else {
            $comment = '{0} is NOT running' -f $service.Name
        }
    }
    catch {
        $comment = 'Issue getting service {0}. {1}' -f $sn, $_
    }

    [pscustomobject]@{
        Name     = $sn
        Comment = $comment
    }
}

or

$obj = [pscustomobject]@{
    Name     = $null
    Comment = $null
}

$sName = 'WSearch', 'BadName'
$results = foreach ($sn in $sName) {
    $obj = $obj.PSObject.Copy()
    $obj.Name = $sn
    try {
        $service = Get-Service -Name $sn -ErrorAction Stop

        if ($service.Status -eq 'Running') {
            $obj.comment = '{0} is running' -f $service.Name
        }
        else {
            $obj.comment = '{0} is NOT running' -f $service.Name
        }
    }
    catch {
        $obj.comment = 'Issue getting service {0}. {1}' -f $sn, $_
    }

    $obj

}

$results

Both product:

Name    Comment
----    -------
WSearch WSearch is running
BadName Issue getting service BadName. Cannot find any service with service name 'BadName'.

Thanks. I got the answer.

Do you want to share with the rest of the class?