Updating a custom object multiple times in a script

Welcome Forums General PowerShell Q&A Updating a custom object multiple times in a script

Viewing 11 reply threads
  • Author
    Posts
    • #222735
      Participant
      Topics: 15
      Replies: 68
      Points: 305
      Rank: Contributor

      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
      
      • This topic was modified 4 weeks, 1 day ago by techsavy83. Reason: code
    • #222744
      Participant
      Topics: 4
      Replies: 2231
      Points: 5,414
      Helping Hand
      Rank: Community MVP

      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”. 😉

    • #222759
      Participant
      Topics: 15
      Replies: 68
      Points: 305
      Rank: Contributor

      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 +=

    • #222765
      Participant
      Topics: 4
      Replies: 2231
      Points: 5,414
      Helping Hand
      Rank: Community MVP

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

    • #222807
      Participant
      Topics: 15
      Replies: 68
      Points: 305
      Rank: Contributor

      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
              }
      }
      
    • #222816
      Participant
      Topics: 4
      Replies: 2231
      Points: 5,414
      Helping Hand
      Rank: Community MVP

      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
    • #222825
      Participant
      Topics: 15
      Replies: 68
      Points: 305
      Rank: Contributor

      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.

    • #222834
      Participant
      Topics: 4
      Replies: 2231
      Points: 5,414
      Helping Hand
      Rank: Community MVP

      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.

      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? 😉

      … what is the most efficient way to do so.

      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. 😉

    • #222873
      Participant
      Topics: 3
      Replies: 310
      Points: 1,016
      Helping Hand
      Rank: Community Hero

      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.

    • #222876
      Participant
      Topics: 12
      Replies: 1607
      Points: 2,495
      Helping Hand
      Rank: Community Hero
      $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'.
      
    • #223557
      Participant
      Topics: 15
      Replies: 68
      Points: 305
      Rank: Contributor

      Thanks. I got the answer.

    • #223584
      Participant
      Topics: 3
      Replies: 310
      Points: 1,016
      Helping Hand
      Rank: Community Hero

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

Viewing 11 reply threads
  • You must be logged in to reply to this topic.