如何将VM标记添加到输出文本文件中

时间:2017-01-11 19:08:15

标签: powershell powercli

我正在获取VMWare环境中所有快照的列表,我正在格式化列表以获取" VM,Name,Created,SizeGB"我也想从这些VM获取vmware服务器标签信息,但我不知道如何做到这一点。我想获取标签信息并将其置于" SizeGB"当列表格式化时。有没有办法做到这一点?

这是我没有标签信息的脚本:

# Adding PowerCLI Snap-in to use cmdlets to connect to vSphere
Add-PSSnapin VMware.VimAutomation.Core

# Connect to vCenter
Connect-ViServer -server $vCenter -ErrorAction Stop 

# Write header on report
Write-Output "VMWare Snapshot Report for $(get-date -f MM-dd-yyyy)" |
    Out-File $Log -Append

# Get VM Snapshot Information for all Snapshots and send that information to
# c:\automation\AllSnapshots.txt
Get-VM | Get-Snapshot | Where-Object {
    $_.Created -lt (Get-Date).AddDays(-3)
} | Format-List vm, name, created, sizegb | Out-File $Log -Append

# Disconnect from vCenter
Disconnect-VIServer -Server * -Force -Confirm:$false

1 个答案:

答案 0 :(得分:0)

# Adding PowerCLI Snap-in to use cmdlets to connect to vSphere
Add-PSSnapin VMware.VimAutomation.Core

# Connect to vCenter
Connect-ViServer -server $vCenter -ErrorAction Stop 

# Write header on report
Write-Output "VMWare Snapshot Report for $(get-date -f MM-dd-yyyy)" |
    Out-File $Log -Append

# Get VM Snapshot Information for all Snapshots and send that information to
# c:\automation\AllSnapshots.txt
$output = @()
foreach ($vm in Get-VM) {
   $tags = ((Get-TagAssignment -Entity $vm | select -ExpandProperty Tag).Name -join ", ")
   foreach ($snapshot in $vm | Get-Snapshot | Where-Object { $_.Created -lt (Get-Date).AddDays(-3) }) {
       $obj = [PSCustomObject]@{VM = $vm.Name; Name = $snapshot.Name; Created = $snapshot.Created; SizeGB = $snapshot.SizeGB; Tags = $tags}
       $output += $obj
   }
}
$output | Format-List | Out-File $Log -Append

# Disconnect from vCenter
Disconnect-VIServer -Server * -Force -Confirm:$false