Tuesday, November 8, 2016

Some useful PowerCLI one liner scripts

In this post I would list some of the useful PowerCLI one liner scripts that I use time to time... some scripts are taken from other blogs so the credit of those scripts goes to their respective authors...

Open the PowerCLI and connect to vCenter server using Connect-VIServer cmdlet, then

Get VMs with connected VLAN and other details,

Get-Cluster "clustername" | get-vmhost "hostname" | get-vm | Get-NetworkAdapter | Format-Table parent, networkname, type, MACaddress

To create table with renamed property name, use @{Name="New_Name";Expression={$_.Old_Name}}
Like in above script,

Get-Cluster "clustername" | get-vmhost "hostname" | get-vm | Get-NetworkAdapter | Format-Table @{Name="VirtualMachine";Expression={$_.parent}}, @{Name="VLAN";Expression={$_.networkname}}

To list all harddisks of a VM with size,

Get-VM VM01 | Get-HardDisk | ft Parent, Name, Filename, CapacityKB –AutoSize

And if you want to export this to a CSV file then,

Get-VM VM01 | Get-HardDisk | Select Parent, Name, Filename, CapacityKB | Export-csv C:\file.csv

We can't export output of Format-Table cmdlet to CSV file so we need to use Select-Object instead.

Add PortGroup to all hosts in cluster with PowerCLI

Get-Cluster “clustername” | Get-VMHost | Get-VirtualSwitch -Name “vSwitch_name″ | New-VirtualPortGroup -Name “VLAN-xx” -VLanId xx

Check Multi-path policy/configuration of connected storage,

Get-VMHost | Get-ScsiLun | Select VMHost, ConsoleDeviceName, Vendor, MultipathPolicy, LunType

To get list of VMs with snapshot,

Get-VM | Get-Snapshot | Select VM,Name,Created,sizemb

List of VMs having snapshot older than 3 days,

Get-VM | Get-Snapshot | Select VM,Name,Created,sizemb | Where {$_.Created -lt ((Get-Date).AddDays(-2))}

To remove snapshot older than 3 days,

Get-Snapshot | Select VM,Name,Created,sizemb | Where {$_.Created -lt ((Get-Date).AddDays(-2))} | Remove-Snapshot

To list time on all VMhosts,

Get-VMHost | sort Name | select Name,@{Name="Current VMHost Time";Expression={(Get-View 

To find a list of VMs having sync time with host option selected,

Get-View -viewtype virtualmachine -Filter @{'Config.Tools.SyncTimeWithHost'='True'} | select name 

That's it for now... Over time I would add more scripts here... :)

No comments:

Post a Comment