如何将值连接到Select-Object的输出

时间:2018-03-13 14:35:26

标签: powershell

我有一个脚本可以找到超过3天及以下的快照,这是我的代码和输出。但是,我想为显示该快照的实际年龄的每个VM添加一个新列,例如5天或4天。我已经尝试通过从今天的日期减去创建的日期来获得年龄。但我不知道如何将它作为列添加到我的输出中。

我用它来计算年龄:

$StartDate = Get-Date

$created = Get-VM |
           Get-Snapshot |
           Where {$_.Created -lt (Get-Date).AddDays(-1)} |
           Select-Object Created

$age = New-Timespan -Start $StartDate -End $created

完整代码:

Add-PSSnapin VMware.VimAutomation.Core

# HTML formatting
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}"
$a = $a + "</style>"

Connect-VIServer -Server ***** -User ****** -Password ******

# Main section of check
Write-Host "Checking VMs for for snapshots"

$date = Get-Date
$datefile = Get-Date -UFormat '%m-%d-%Y-%H%M%S'

$filename = "C:\Temp\snaps_older_than_3\" + $datefile + ".htm"

$created = Get-VM |
           Get-Snapshot |
           Where {$_.Created -lt (Get-Date).AddDays(-1)} |
           Select-Object Created

$age = New-Timespan -Start $StartDate -End $created

$ss = Get-VM |
      Get-Snapshot |
      Where {$_.Created -lt (Get-Date).AddDays(-1)} |
      Select-Object vm, name, SizeGB, SizeMB, Created, powerstate + $age |
      ConvertTo-HTML -Head $a -Body "<H2>VM Snapshot Report </H2>"|
      Out-File $filename

Write-Host "   Complete " -ForegroundColor Green
Write-Host "Your snapshot report has been saved to:" $filename

$SMTPServer = "*******"
$SMTPPort = 25
$username = "vcenter@mmmm.com"

#Define the receiver of the report
$to = "mmmmm@hcl.com"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = New-Object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.Subject = $subject
$message.Body = $body
$message.To.Add($to)
$message.From = $username
$message.Attachments.Add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
$smtp.Send($message)

Write-Host "Mail Sent"

输出:

enter image description here

我想添加一个名为“age”的新列。

1 个答案:

答案 0 :(得分:2)

使用计算属性:

Get-VM |Select-Object VM,Name,SizeGB,SizeMB,Created,PowerState,@{Name='Age';Expression={New-TimeSpan -Start $StartDate -End $_.Created}}

来自help text for Select-Object

  

-Property
  指定要选择的属性。允许使用通配符。

     

Property参数的值可以是新的计算属性。   要创建计算属性,请使用哈希表。有效密钥是:

     
      
  • 姓名(或标签)<string>
  •   
  • 表达式<string><script block>
  •