-1

I need to create an object and each iteration add values to. The problem what i have is I thing with the logic of the code. I think I have to create another foreach and place New-Object psobject -Property $object outside...but i don't know how to do it.

Can someone help me?

Import-Module BEMCLI  #BackupExec

$object= @{}
#For each last 15 job backups
ForEach ($i in $(Get-BEJob "FULL" | Get-BEJobHistory -FromStartTime (Get-Date).AddDays("-15") -JobType Backup))
 { 

 $object.TAPE= ($i | Get-BEJobLog | Get-BEJobLogFiles) # get Tape
 $object.START_TIME=$i.StartTime #get starttime
 $object.END_TIME=$i.EndTime #get endtime

 New-Object psobject -Property $object
 } 

$object | ft
user2637202
  • 113
  • 4
  • 11
  • "I need to create an object and each iteration add values to".. What? All BEJobs in the same single object? What output are you looking for? The usual solution is to create an object per BEJob and collect them in an array (list of objects). – Frode F. Mar 13 '16 at 12:20
  • Yes, you are right. I still struggle with objects and arrays. Thanks. – user2637202 Mar 13 '16 at 12:28
  • [Powershell: Everything you wanted to know about PSCustomObject](https://kevinmarquette.github.io/2016-10-28-powershell-everything-you-wanted-to-know-about-pscustomobject/) – KyleMit Sep 04 '18 at 20:50
  • Possible duplicate of [Powershell: How to create custom object and pass it to function in powershell?](https://stackoverflow.com/questions/35904863/powershell-how-to-create-custom-object-and-pass-it-to-function-in-powershell) – KyleMit Sep 04 '18 at 21:34

2 Answers2

1

Create another Array Object, and add your $object data into it on every iteration

Import-Module BEMCLI  #BackupExec

$Array = @()
$object= @{}
#For each last 15 job backups
ForEach ($i in $(Get-BEJob "FULL" | Get-BEJobHistory -FromStartTime (Get-Date).AddDays("-15") -JobType Backup))
 { 

 $object.TAPE= ($i | Get-BEJobLog | Get-BEJobLogFiles) # get Tape
 $object.START_TIME=$i.StartTime #get starttime
 $object.END_TIME=$i.EndTime #get endtime

 $Array += $Object
 } 

$Array | ft
Avshalom
  • 8,657
  • 1
  • 25
  • 43
0

That foreach construct you have looks like it is designed to send data down the pipeline. Not only are you not attempting to capture the data it does not send items down the pipeline anyway. The simplest thing to change would be to assign the foreach loop to a variable

Import-Module BEMCLI  #BackupExec

#For each last 15 job backups
$objects = ForEach ($i in $(Get-BEJob "FULL" | Get-BEJobHistory -FromStartTime (Get-Date).AddDays("-15") -JobType Backup))
{ 
    $object = @{} # Wipe object for next run. 
    $object.TAPE= ($i | Get-BEJobLog | Get-BEJobLogFiles) # get Tape
    $object.START_TIME=$i.StartTime #get starttime
    $object.END_TIME=$i.EndTime #get endtime

    New-Object psobject -Property $object
} 

$objects | ft
Matt
  • 45,022
  • 8
  • 78
  • 119