简体   繁体   English

消息正文中的 PowerShell Send-MailMessage 格式列

[英]PowerShell Send-MailMessage format column in message body

Warning - I'm new to PowerShell.警告 - 我是 PowerShell 的新手。 There are two outcomes I would like to achieve with this script.我想用这个脚本实现两个结果。 The first is to include the output in an email and format the columns in the message body so they align with the headers similar to Out-Host.第一种是将输出包含在电子邮件中,并格式化邮件正文中的列,使它们与类似于 Out-Host 的标题对齐。 Second is when out-csv, out-gridview or export-excel, how do I order the columns?其次是当 out-csv、out-gridview 或 export-excel 时,我如何对列进行排序?

$VolArray = @();


$Volumes = Get-Ncvol | Where-Object {$_.VolumeMirrorAttributes.IsDataProtectionMirror -match 'False' -and $_.VolumeStateAttributes.IsVserverRoot -match 'False' -and -not $_.VolumeCloneAttributes.VolumeCloneParentAttributes}
    ForEach ($Volume in $Volumes){
        #get properties
        $vol = Get-Ncvol $Volume
        #create object with values
        $volobj = New-Object -TypeName PSObject -Property @{
            'Controller' = $vol.NcController
            'Vserver' = $vol.Vserver
            'Aggregate' = $vol.VolumeIdAttributes.ContainingAggregateName 
            'Name' = $vol.VolumeIdAttributes.Name 
            'Type' = $vol.VolumeIdAttributes.Type 
            'TotSizeGB'= $vol.VolumeSpaceAttributes.Size/1gb
            'Used' = $vol.VolumeSpaceAttributes.SizeUsed/1gb
            '%Used' = $vol.VolumeSpaceAttributes.PercentageSizeUsed
            'AvailableGB' = $vol.VolumeSpaceAttributes.SizeAvailable/1gb
            'SSResSizeGB' = $vol.VolumeSpaceAttributes.SnapshotReserveSize/1GB 
            'IsDPMirror' = $vol.VolumeMirrorAttributes.IsDataProtectionMirror 
            'IsReplicaVol' = $vol.VolumeMirrorAttributes.IsReplicaVolume 
            'IsDPSource' = $vol.VolumeMirrorAttributes.IsSnapmirrorSource 
            'DPInProgress' = $vol.VolumeMirrorAttributes.MirrorTransferInProgress
            'SSPolicy' = $vol.VolumeSnapshotAttributes.SnapshotPolicy 
            'AutoSSEnabled' = $vol.VolumeSnapshotAttributes.AutoSnapshotsEnabled 
            'SSCount' = $vol.VolumeSnapshotAttributes.SnapshotCount
            '%SSReserve' = $vol.VolumeSpaceAttributes.PercentageSnapshotReserve 
            '%SSResUsed' = $vol.VolumeSpaceAttributes.PercentageSnapshotReserveUsed
            'SSSpaceUsed' = $vol.VolumeSpaceAttributes.SizeUsedBySnapshots/1GB;

        }
        #add to array outside opf for-loop
        $VolArray += $volobj

    } 


    #$VolArray | Export-Csv -Path c:\temp\file.csv
    #$VolArray | Export-Excel -Path c:\temp\exceldump.xlsx
    $VolArray | Out-String

#Send-MailMessage -To $mailto -Subject $subject -Body (-join $message) -Port $port -SmtpServer $smtp -from $emailfrom 
Send-MailMessage -To $mailto -Subject $subject -Port $port -SmtpServer $smtp -from $emailfrom -Attachments c:\temp\file.csv 

Message body:邮件正文: 邮件正文

Column ordering列排序

In PowerShell, for performance reasons, there is no guarantee of order for properties of common hashtables.在 PowerShell 中,出于性能原因,无法保证常见哈希表的属性顺序。 Thankfully you can use the [ordered] keyword to create ordered dictionaries (a hashtable is a form of dictionary) since version 3.幸运的是,从版本 3 开始,您可以使用[ordered]关键字来创建有序字典(哈希表是字典的一种形式)。

[PSCustomObject][ordered]@{
    FirstColumn  = 1
    SecondColumn = 2
    ThirdColumn = 3
}

This will ensure the order of the properties in subsequent operations like Export-Csv.这将确保后续操作(如 Export-Csv)中的属性顺序。 Note that I also used the [PSCustomObject] accelerator, which is more efficient and than New-Object -TypeName PSObject .请注意,我还使用了[PSCustomObject]加速器,它比New-Object -TypeName PSObject更高效。

Getting the data efficiently高效获取数据

In your code there are unnecessary calls to Get-Ncvol in the foreach loop.在您的代码中,在 foreach 循环中有不必要的Get-Ncvol调用。 You already have the data you need form earlier:您已经获得了您之前需要的数据:

$Volumes = Get-Ncvol |
Where-Object {
    $_.VolumeMirrorAttributes.IsDataProtectionMirror -match 'False' -and
    $_.VolumeStateAttributes.IsVserverRoot -match 'False' -and
    -not $_.VolumeCloneAttributes.VolumeCloneParentAttributes
}

# Store results in a variable to use later
$reportData = foreach ($Volume in $Volumes) {
    # Create object with values
    [PSCustomObject][ordered]@{
        'Controller'    = $Volume.NcController
        'Vserver'       = $Volume.Vserver
        'Aggregate'     = $Volume.VolumeIdAttributes.ContainingAggregateName 
        'Name'          = $Volume.VolumeIdAttributes.Name 
        'Type'          = $Volume.VolumeIdAttributes.Type 
        'TotSizeGB'     = $Volume.VolumeSpaceAttributes.Size / 1gb
        'Used'          = $Volume.VolumeSpaceAttributes.SizeUsed / 1gb
        '%Used'         = $Volume.VolumeSpaceAttributes.PercentageSizeUsed
        'AvailableGB'   = $Volume.VolumeSpaceAttributes.SizeAvailable / 1gb
        'SSResSizeGB'   = $Volume.VolumeSpaceAttributes.SnapshotReserveSize / 1GB 
        'IsDPMirror'    = $Volume.VolumeMirrorAttributes.IsDataProtectionMirror 
        'IsReplicaVol'  = $Volume.VolumeMirrorAttributes.IsReplicaVolume 
        'IsDPSource'    = $Volume.VolumeMirrorAttributes.IsSnapmirrorSource 
        'DPInProgress'  = $Volume.VolumeMirrorAttributes.MirrorTransferInProgress
        'SSPolicy'      = $Volume.VolumeSnapshotAttributes.SnapshotPolicy 
        'AutoSSEnabled' = $Volume.VolumeSnapshotAttributes.AutoSnapshotsEnabled 
        'SSCount'       = $Volume.VolumeSnapshotAttributes.SnapshotCount
        '%SSReserve'    = $Volume.VolumeSpaceAttributes.PercentageSnapshotReserve 
        '%SSResUsed'    = $Volume.VolumeSpaceAttributes.PercentageSnapshotReserveUsed
        'SSSpaceUsed'   = $Volume.VolumeSpaceAttributes.SizeUsedBySnapshots / 1GB;
    }
}

Exporting & emailing导出和发送电子邮件

Since we already took care of the column ordering you just need to use $reportData | Export-Csv c:\\temp\\file.csv -NoTypeInformation由于我们已经处理了列排序,因此您只需要使用$reportData | Export-Csv c:\\temp\\file.csv -NoTypeInformation $reportData | Export-Csv c:\\temp\\file.csv -NoTypeInformation or the Export-Excel equivalent. $reportData | Export-Csv c:\\temp\\file.csv -NoTypeInformationExport-Excel等效项。

Emailing is going to be a bit more difficult.发送电子邮件将变得更加困难。 Your best bet to convert the data to an HTML table and include it as the body of the email.最好的办法是将数据转换为 HTML 表格并将其包含在电子邮件正文中。

# The CSS is neccesary to make the table look nicer, adjust as needed
$css = @'
<style>
  body {background-color: powderblue;}
  h1 {color: red;}
  p {color: blue;}
  th, td { 
    padding: 15px;
    text-align: left;
  }
</style>
'@

$emailBody = $reportData | ConvertTo-Html -Head $css

# Use parameter splatting for redability
$emailParameters = @{
    To         = "jdoe@company.com" 
    Subject    = "NetApp report for $(Get-Date -Format 'd')"
    Body       = $emailBody
    BodyAsHtml = $true
    SmtpServer = "smtp.company.com"
    Credential = Get-Credential 
}
Send-MailMessage @emailParameters

[Ordered] worked perfectly. [已订购] 完美运行。

I modified the message body parameter: Body = ($emailBody | Out-String)我修改了邮件正文参数:Body = ($emailBody | Out-String)

Because of this error:因为这个错误:

Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.

Would you have any recommendations for setting the number of decimal places?您对设置小数位数有什么建议吗? ...124.994548797607421875 ...124.994548797607421875

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM