使用PowerShell将数据写入31天中的每一天

时间:2015-04-10 09:49:21

标签: powershell

基本上我使用PowerShell从备份软件中获取数据,然后将其写入表中。我对这部分没有任何问题,因为我正在获取一天的数据,然后将其写入一个表中,其中行是服务器名称,列显示"成功"或者"失败"。

我希望能够创建一个表,其中行显示服务器名称,列显示第1天到第31天,然后"成功"或"失败"每一天。我希望这是有道理的。

$format = "<style>"
$format = $format + "{font-family: Arial; font-size: 10pt;}"
$format = $format + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$format = $format + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$format = $format + "TD{border: 1px solid black; padding: 5px; }"
$format = $format + "</style>"

$sessions = Get-VBRBackupSession | Where-Object {$_.JobType -eq "Backup" -and $_.EndTime -ge (Get-Date).addhours(-24)}
$realsessions = $sessions.gettasksessions()

$table = @()

foreach ($session in $realsessions) {


$backupobject = New-Object PSObject
$backupobject | Add-Member -MemberType NoteProperty -Name "Job Name" -Value $session.JobName
$backupobject | Add-Member -MemberType NoteProperty -Name "Server Name" -Value $session.Name
$backupobject | Add-Member -MemberType NoteProperty -Name "Backup Status" -Value $session.Status

$table += $backupobject

}
$table | ConvertTo-Html -Head $format -body "<H2>Veeam Backup Report</H2>" | Out-File "C:\Temp\VeeamBackupReport.xls"

$ sessions的输出:

BottleneckManager         : CJobBottleneckManager
Info                      : Veeam.Backup.Model.CBackupSessionInfo
Progress                  : Veeam.Backup.Model.CBackupProgressData
StartupMode               : Normal
JobSourceType             : VDDK
CurrentPointId            : 0b833e92-0f45-4b75-bb40-f8c80a696df9
OriginalSessionId         : 5bfdc2bf-d17b-40aa-9e5f-d5e44b19ca67
IsFullMode                : False
IsRetryMode               : False
IsVeeamZip                : False
PostActivity              : AskService
Name                      : Daily_Backups
OrigJobName               : Daily_Backups
BackupStats               : Veeam.Backup.Model.CBackupStats
WorkDetails               : Veeam.Backup.Core.CBackupSessionWorkDetails
WillBeRetried             : False
IsManuallyStopped         : False
StorageVerificationResult : Veeam.Backup.Core.CStorageVerificationResultContainer
SessionInfo               : Veeam.Backup.Model.CBackupSessionInfo
Id                        : 5bfdc2bf-d17b-40aa-9e5f-d5e44b19ca67
JobType                   : Backup
JobName                   : Daily_Backups
JobSpec                   :
JobTypeString             : Other job type
Operation                 :
Description               :
BaseProgress              : 100
IsCompleted               : True
IsWorking                 : False
JobId                     : 843d4014-5dda-4dfb-8590-949d7ed843ce
Result                    : Success
State                     : Stopped
EndTime                   : 2015/04/11 04:12:36 AM
CreationTime              : 2015/04/10 10:00:20 PM
AuxData                   : <AuxData><CBackupStats><BackupSize>46279333376</BackupSize><DataSize>97487622667</DataSize>
                            <DedupRatio>99</DedupRatio><CompressRatio>47</CompressRatio></CBackupStats><CBackupSessionW
                            orkDetails><WorkDuration>223365199270</WorkDuration></CBackupSessionWorkDetails></AuxData>
IsLowerAgentPriority      : True
LogName                   : Job.Daily_Backups
LogsSubFolder             : Daily_Backups
Logger                    : Veeam.Backup.Core.XmlLogger
Tracer                    : Veeam.Backup.Core.CSessionLogTracer

$ RealSessions的输出

JobSess         : Veeam.Backup.Core.CBackupSession
Info            : Veeam.Backup.Model.CBackupTaskSessionInfo
ProgressManager : Veeam.Backup.Core.CBackupTaskSessionProgress
WorkTimer       : Veeam.Backup.Core.CBackupTaskSessionWorkTimer
Id              : 3767cd65-8de9-423e-b77e-6850ebb95dab
Name            : Server1
Status          : Success
Operation       :
Progress        : Veeam.Backup.Model.CBackupProgressData
CurrentDiskNum  : 1
Logger          : Veeam.Backup.Core.XmlLogger
Tracer          : Veeam.Backup.Core.CSessionLogTracer
WillBeRetried   : False
RetryCounter    : 0
JobSessId       : 5bfdc2bf-d17b-40aa-9e5f-d5e44b19ca67
JobName         : Daily_Backups

2 个答案:

答案 0 :(得分:0)

不确定您要完成什么,但我会考虑使用逻辑来根据月份来备份您的信息。如果月份是新的,那么我们使用不同的文件。这将与31天的要求大致保持一致。你提到你对CSV输出没问题但是我已经太过分了,所以让我们保持HTML输出。我无法访问Get-VBRBackupSession,但您应该很难将此代码与您的cmdlet结合使用。

function ConvertFrom-HTMLTable{
    param(
        [string]$Path
    )
    $regex = "(?s)<TABLE>.*?</TABLE>"
    $fileContent = Get-Content $Path -Raw 
    $table = (Select-String -InputObject $fileContent -Pattern $regex).Matches.Value -split "`r`n"
    $properties = ($table | Where-Object{$_ -match '^\<tr\>\<th\>'}) -split '</?th>|</?tr>' | Where-Object{$_}

    $table | Where-Object{$_ -match '^\<tr\>\<td\>'} | ForEach-Object{
        $values = $_ -split '</?td>|</?tr>' | Where-Object{$_}
        $props = @{}
        for($propIndex = 0; $propIndex -lt $properties.Count; $propIndex++){
            $props."$($properties[$propIndex])" = $values[$propIndex]
        }

        [pscustomobject]$props
    }
}


$body = "<H2>Veeam Backup Report</H2>"
$head = @"
<style>"
    {font-family: Arial; font-size: 10pt;}
    TABLE{border: 1px solid black; border-collapse: collapse;}
    TH{border: 1px solid black; background: #dddddd; padding: 5px; }
    TD{border: 1px solid black; padding: 5px; }
</style>
"@

$date = get-date -Format "MMMyyyy"
$outputFile = "C:\Temp\VeeamBackupReport$date.html"
$outputData = @()
If(Test-Path $outputFile){
     $outputData = ConvertFrom-HTMLTable $outputFile
}

$result = Get-ChildItem c:\temp -File | Select-Object Name,Length,LastWriteTime,@{Label="Fluff";Expression={get-date -format "mm"}}
$outputData + $result | Select-Object Name,Length,LastWriteTime,Fluff | 
    ConvertTo-Html -Head $format -Body $body | 
    Set-Content $outputFile

我们看看是否已存在此月/年组合的文件。如果我们对它运行ConvertFrom-HTMLTable以获取包含我们将要导出的相同属性的自定义对象。获得新结果后,我们将输出结合起来并将它们返回到文件中。

我使用Get-ChildItem输出进行测试,并显示可以向输出添加自定义字段。同样,您应该能够使用自己的代码进行调整。您应该能够在没有任何更改的情况下运行此代码,并等待一两分钟再次运行它以查看发生了什么。

答案 1 :(得分:0)

我要补充一个答案。虽然我的另一个答案对你的情况不正确,但我想留下它,以防它为别人增加价值。

我们需要做的是在保留$realsessions来自endtime原始输出的Get-VBRBackupSession时取出所有$days = 31 $sessions = Get-VBRBackupSession | Where-Object {$_.JobType -eq "Backup" -and $_.EndTime -ge (Get-Date).AddDays(-$days)} $realsessions = $sessions | ForEach-Object{ # Get session information $endtime = [datetime]$_.EndTime # Create a custom object for each real session that keeps some session info. $_.gettasksessions() | ForEach-Object{ New-Object -TypeName PSCustomObject -Property @{ ServerName = $_.Name JobName = $_.JobName BackupStatus = $_.Status EndTime = $endtime } } } # You should check the content of $realsessions to be sure it is organized right $realsessions | Group-Object ServerName | ForEach-Object{ # Collect the server group $serverGroup = $_.Group # Start building the object using the first element $props = @{ ServerName = $serverGroup[0].Name JobName = $serverGroup[0].JobName } # Cycle the days and populate the status columns for($daysIndex = 1; $daysIndex -le $days;$daysIndex++){ $props.$daysIndex = $serverGroup | Where-Object{((Get-Date).Date - ($_.Endtime).Date) -eq $daysIndex} | Select-Object -ExpandProperty Status } # Output the new object to the pipe. New-Object -TypeName PSCustomObject -Property $props } | Export-Csv -Path "C:\Temp\VeeamBackupReport.csv" -NoTypeInformation

Get-VBRBackupSession

由于我无法访问{{1}},因此我需要您进行调试,以便我们知道哪些方向正确。