how to combile two variable in single output in for loop ? in powershell

Viewed 79

Just tried to get the below script output as excel/csv file . goal is to get all the data in column format

$date = (Get-Date).AddHours(-24)
$sessions = Get-VBRComputerBackupJobSession
foreach ($PBackup_job in (Get-VBRComputerBackupJob | Select Name))
 {  $PBackup_job_name = $PBackup_job.Name
    write "------------   Physical Server Backup Job Name : $PBackup_job_name   ------------"
    $sessions | where {$_.CreationTime -ge $date} | sort CreationTime | Select CreationTime, endtime, result, state | Format-Table
    } ```


please help to het the desired output




  original output [1]: https://i.stack.imgur.com/sKqRq.png
  required output [2]: https://i.stack.imgur.com/3hh9B.png
1 Answers
$date = (Get-Date).AddHours(-24)
$sessions = Get-VBRComputerBackupJobSession | `
    Where-Object { $_.CreationTime -ge $date } | `
    Sort-Object CreationTime | `
    Select-object CreationTime, endtime, result, state

$output = @()
foreach ($PBackup_job in (Get-VBRComputerBackupJob | Select-object Name)) {
   
    $result = [PSCustomObject]@{
        JobName      = $PBackup_job.Name
        CreationTime = $sessions.CreationTime
        EndTime      = $sessions.EndTime
        Result       = $sessions.result
        state        = $sessions.state
    }
    
    $output += $result
} 

$output | Format-Table

I haven't tested this code, but using pscustomobject makes the job simple. You can also pipe the output to Export-csv file.

Related