PowerCLI
This is a list of PowerCLI bits I have picked up along the way.  90% of these were found via Google, I apologize for not having credits for each. Most are simple one-liners that perform particular tasks.  It is typically easy to insert these bits into a larger scripts that loop through hosts, target specific VMs or just link them together to run multiple commands at once.
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 | # Add PowerCLI Core snapinIf(!(Get-PSSnapin-nameVMware.VimAutomation.Core-ErrorActionSilentlyContinue)) {    Add-PSSnapinVMware.VimAutomation.Core}# Add PowerCLI vCD snapinIf(!(Get-PSSnapin-nameVMware.VimAutomation.Cloud-ErrorActionSilentlyContinue)) {    Add-PSSnapinVMware.VimAutomation.Cloud}# Add PowerCLI VDS snapinIf(!(Get-PSSnapin-nameVMware.VimAutomation.VDS-ErrorActionSilentlyContinue)) {    Add-PSSnapinVMware.VimAutomation.VDS}# Connect to vCenterConnect-VIServervcenternameorip# Disconnect from vCenterDisconnect-VIServervcenternameorip-Confirm:$False# Connect to vCDConnect-CIServermy.vcd.url# Disconnect from vCDDisconnect-CIServermy.vcd.url-Confirm:$False# Connected VI Servers$DefaultVIServers# Number of Connected VI Servers$DefaultVIServers.Count# PowerCli VersionGet-PowerCLIVersion# PowerCLI ConfigurationGet-PowerCLIConfiguration# VMHosts# Change ESXi root password (or any other local user)$VMHosts= Get-VMHostForEach($VMHostin$VMHosts){    $HostName= $VMHost.Name    Connect-VIServer$HostName-Userroot-passwordP@ssw0rd    Set-VMHostAccount-UserAccountroot-passwordN3wPassword    Disconnect-VIServer-Server$HostName-Confirm:$False}#Check Lockdown mode statusGet-VMHost| Select Name, @{Name="LockdownModeEnabled";Expression={($_).Extensiondata.Config.adminDisabled}} | ft-auto#Disable Lockdown modeGet-VMHost| %{($_| get-view).ExitLockdownMode()}#Enable Lockdown modeGet-VMHost| %{($_| get-view).EnterLockdownMode()}# Start ESXi SSH ServiceGet-VMHost| Foreach{Start-VMHostService-HostService($_| Get-VMHostService| Where { $_.Key -eq"TSM-SSH"} )}# Stop ESXi SSH ServiceGet-VMHost| Foreach{Stop-VMHostService-HostService($_| Get-VMHostService| Where { $_.Key -eq"TSM-SSH"} )-Confirm:$false}# View SSH Service stateGet-VMHost| Get-VMHostService| Where { $_.Key -eq"TSM-SSH"} | Select VMHost, Label, Policy, Running | ft-auto#Enable SSH Server firewall exceptionGet-VMHost| Get-VMHostFirewallException| Where {$_.Name -eq"SSH Server"} | Set-VMHostFirewallException-Enabled:$true# Sets remote syslog server# Set Hostd logging level to info (default is verbose)Get-VMHost| Get-AdvancedSetting-NameConfig.HostAgent.log.level | Set-AdvancedSetting-Value"info"-Confirm:$false# Set Vpxa logging level to info (default is verbose)(must be connected to VC)Get-VMHost| Get-AdvancedSetting-NameVpx.Vpxa.config.log.level | Set-AdvancedSetting-Value"info"-Confirm:$false# Reset syslog service$esxcli= Get-EsxCli-VMHostservername$esxcli.system.syslog.reload()# Sets ESXi syslog server firewall exceptionGet-VMHost| Get-VMHostFirewallException|?{$_.Name -eq'syslog'} | Set-VMHostFirewallException-Enabled:$true# Backup ESXi Host ConfigGet-VMHostMyESXiHost | Get-VMHostFirmware-BackupConfiguration-DestinationPath“F:\”# Restore ESXi Host ConfigGet-VMHostMyESXiHost | Set-VMHost-StateMaintenance | Set-VMHostFirmware-Restore-SourcePath“F:\”# Reset ESXi Host to defaultsGet-VMHostMyESXiHost | Set-VMHostFirmware-ResetToDefaults# Gather Log Bundle from HostGet-VMHostMyESXiHost | Get-Log-Bundle-DestinationPath“F:\”# Gather Individual LogsGet-VMHostMyESXiHost | Get-Loghostd | Select-ExpandPropertyEntries | Out-File“F:\hostd.log”Get-VMHostMyESXiHost | Get-Logvpxa | Select-ExpandPropertyEntries | Out-File“F:\vpxa.log”# Get the time on all ESXi hostsGet-VMHost| Select Name,@{Name="Time";Expression={(get-view$_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}# Set the time on all ESXi hosts to the PowerCLI host's timeGet-VMHost| %{(Get-View$_.ExtensionData.configManager.DateTimeSystem).UpdateDateTime((Get-Date-formatu)) }# Rescan HBA AdaptersForeach($esxinGet-VMhost-LocationClusterName | sort Name) { $esx| Get-VMHostStorage-RescanAllHBA-rescanVMFS-refresh}# Retrieve ntp serversGet-VMHost| Select Name, @{N="NTPServer";E={$_| Get-VMHostNtpServer}}, @{N="ServiceRunning";E={(Get-VmHostService-VMHost$_| Where-Object{$_.key -eq"ntpd"}).Running}}# Replace ntp servers on hosts$oldntpservers= "192.168.0.1","192.168.0.2"$newntpservers= "192.168.0.20","192.168.0.21"Foreach($vmhostinGet-VMHost){    #stop ntpd service    $vmhost|Get-VMHostService |?{$_.key -eq"ntpd"}|Stop-VMHostService-Confirm:$false    #remove ntpservers    $vmhost|Remove-VMHostNtpServer-NtpServer$oldntpservers-Confirm:$false    #add new ntpservers    $vmhost|Add-VmHostNtpServer-NtpServer$newntpservers    #start ntpd service    $vmhost|Get-VMHostService |?{$_.key -eq"ntpd"}|Start-VMHostService}# Configure ntp service to start and stop with hostGet-VMHost| Get-VMHostService| ?{$_.key -eq"ntpd"} | Set-VMHostService-Policy"on"-confirm:$false# Change DNS servers, domain name and search suffixGet-VMHost| Get-VMHostNetwork| Set-VMHostNetwork-DnsAddress[DNS1 IP address],[DNS2 IP address]-Domain[Domain name]-SearchDomain[Search domain name]# Enter Maintenance ModeGet-VMHost| Set-VMHost-StateMaintenance#Add hosts to domainGet-VMHost| Get-VMHostAuthentication| Set-VMHostAuthentication-Domaindomain-Userdomainuser-Passwordpassword-JoinDomain-Confirm:$false#Remove hosts from domainGet-VMHost| Get-VMHostAuthentication| Set-VMHostAuthentication-LeaveDomain-Confirm:$false#Check host domain statusGet-VMHost| Get-VMHostAuthentication| Select VMHost, DomainMembershipStatus, Domain | ft-auto# Disconnect and Remove from VCGet-VMHost| Set-VMHost-State Disconnected-Confirm:$false| Remove-VMHost-Confirm:$false# Add into VCAdd-VMHost-Name$VMHost-Location$Location-Credential$cred-Force-Confirm:$false# Join a cluster by moving an ESX host from one location to the cluster.Move-Inventory-Item(Get-VMHost-NameesxHost)-Destination(Get-Cluster-NameclusterName)# VM Stuff# Get VM Information, Cluster, Host, DatastoreGet-VM| Select Name, @{N=”Cluster”;E={Get-Cluster-VM$_}},@{N=”ESX Host”;E={Get-VMHost-VM$_}},@{N=”Datastore”;E={Get-Datastore-VM$_}}# Grab powered on Windows VMs in a particular folderGet-Folder"projects"| Get-VM| Where-Object{$_.Guest.OSFullName -like"*Windows*"-and$_.PowerState -eq"PoweredOn"} | Sort Name# Get VMs with CPU Reservations:Get-VM| Get-VMResourceConfiguration| Where {$_.CpuReservationMhz -ne0} | Select VM,CpuReservationMhz# Get VMs with Memory Reservations:Get-VM| Get-VMResourceConfiguration| Where {$_.MemReservationMB -ne0} | Select VM,MemReservationMB# Reset Memory resource limit to UnlimitedGet-VM| Get-VMResourceConfiguration| Where-Object{$_.MemLimitMB -ne"-1"} | Set-VMResourceConfiguration-MemLimitMB$null# Reset CPU resource limit to UnlimitedGet-VM| Get-VMResourceConfiguration| Where-Object{$_.CpuLimitMhz -ne"-1"} | Set-VMResourceConfiguration-CPULimitMhz$null# Reset both Memory and CPU resource limits to Unlimited (slow)Get-VM| Get-VMResourceConfiguration| Set-VMResourceConfiguration-MemLimitMB$null-CpuLimitMhz$null# Get Running VMs without VMware Tools Installed:Get-View-ViewType“VirtualMachine”-PropertyGuest,name-filter@{“Guest.ToolsStatus”=”toolsNotInstalled”;”Guest.GuestState”=”running”} | Select Name# VMs Created Recently:Get-VIEvent-maxsamples10000 | Where {$_.Gettype().Name -eq“VmCreatedEvent”} | Select createdTime, UserName, FullFormattedMessage# VMs Removed Recently:Get-VIEvent-maxsamples10000 | Where {$_.Gettype().Name -eq“VmRemovedEvent”} | Select createdTime, UserName, FullFormattedMessage# List the last 10 VMs created, cloned or importedGet-VIEvent-maxsamples10000 |where{$_.Gettype().Name-eq"VmCreatedEvent"-or$_.Gettype().Name-eq"VmBeingClonedEvent"-or$_.Gettype().Name-eq"VmBeingDeployedEvent"} |SortCreatedTime-Descending|SelectCreatedTime, UserName,FullformattedMessage-First10# List last 5 VMs removedGet-VIEvent-maxsamples10000 | where {$_.Gettype().Name -eq"VmRemovedEvent"} | Sort CreatedTime-Descending| Select CreatedTime, UserName, FullformattedMessage-First19# List of the VM’s created over the last 14 daysGet-VIEvent-maxsamples10000-Start(Get-Date).AddDays(-14) | where {$_.Gettype().Name-eq"VmCreatedEvent"-or$_.Gettype().Name-eq"VmBeingClonedEvent"-or$_.Gettype().Name-eq"VmBeingDeployedEvent"} |SortCreatedTime-Descending|SelectCreatedTime, UserName,FullformattedMessage# List of the VMs removed over the last 14 daysGet-VIEvent-maxsamples10000-Start(Get-Date).AddDays(-14) |where{$_.Gettype().Name-eq"VmRemovedEvent"} |SortCreatedTime-Descending|SelectCreatedTime, UserName,FullformattedMessage# VMs with more than 2 vCPUs:Get-VM| Where {$_.NumCPU -gt2} | Select Name, NumCPU# Check for invalid of inaccessible VMs:Get-View-ViewTypeVirtualMachine | Where {-not$_.Config.Template} | Where{$_.Runtime.ConnectionState -eq“invalid” -or$_.Runtime.ConnectionState -eq“inaccessible”} | Select Name# vMotion VMMove-VMvm_name-Destination(Get-VMHostesxi_hostname)# Storage vMotion VMGet-VMvm_name | Move-VM-Datastore(Get-Datastoredatastore_name)# Create multiple new VMs from a template$destCluster= Get-Cluster-NameCluster01$destDatastore= Get-DatastoreCluster-NameCluster_Datastore$destFolder= foldername$sourceTemplate= Get-Template-NameW2K12_STD1..6 | Foreach{New-VM-Nametest0$_-ResourcePool$destCluster-Location$destFolder-Template$sourceTemplate-Datastore$destDatastore-RunAsync}# Storage# Bulk storage movesGet-VM-Datastore<SourceDatastore1> | Move-VM-Datastore<TargetDatastore>-runasync# Delete all Snapshots with Certain Name:Get-VM| Get-Snapshot| Where { $_.Name.Contains(“Consolidate”) } | Remove-Snapshot# List all Snapshots:Get-VM| Get-Snapshot| Select VM,Name,Description,Created# List all RDM disksGet-VM| Get-HardDisk-DiskType"RawPhysical","RawVirtual"| Select Parent,Name,DiskType,ScsiCanonicalName,DeviceName# Search datastores for less than x free spaceGet-Datastore| Where-Object{$_.freespaceMB -lt100000}Get-Datastore| Where-Object{$_.freespaceGB -lt500 -and$_.Name -notlike"*localstorage*"}# # of VMs per DatastoreGet-Datastore| Select Name, @{N="NumVM";E={@($_| Get-VM).Count}} | Sort Name# Mount datastore to psdriveNew-PSDrive-name"mounteddatastore"-Root\-PSProviderVimDatastore-Datastore(Get-Datastore$datastore)# Copy files to mounted datastoreCopy-Datastoreitem$patchLocation+ $patch-Destinationmounteddatastore:# Delete file on mounted datastoredel mounteddatastore:$patch# Unmount datastore from psdriveRemove-PSDrive-name"mounteddatastore"-PSProviderVimDatastore# Reload inaccessable VMs after a NFS/iSCSI outageGet-View-ViewTypeVirtualMachine | ?{$_.Runtime.ConnectionState -eq"invalid"-or$_.Runtime.ConnectionState -eq"inaccessible"} | %{$_.reload()}# Get Host HBA WWNsFunctionGet-VMHostHbaWWN{    param( $VMHost)    $EsxHostHba= get-vmhosthba-VMHost$VMHost    foreach( $hbain$EsxHostHba){        $WWN= "{0:x}"-f$hba.PortWorldWideName        $outObj= New-ObjectPSObject        $outObj| Add-Member-MemberTypeNoteProperty-NameName-Value$VMHost        $outObj| Add-Member-MemberTypeNoteProperty-NameWWNDec-Value$hba.PortWorldWideName        $outObj| Add-Member-MemberTypeNoteProperty-NameWWNHex-Value$WWN        $outObj| Add-Member-MemberTypeNoteProperty-NameDevice-Value$hba.Device        $outObj| Add-Member-MemberTypeNoteProperty-NameType-Value$hba.Type        $outObj| Add-Member-MemberTypeNoteProperty-NameModel-Value$hba.Model        $outObj| Add-Member-MemberTypeNoteProperty-NameStatus-Value$hba.Status        $outObj    }}# Networking# Add Port Group “VLAN 500” with VLAN tag 500 to vSwitch1 on all hosts in a ClusterForeach($esxinGet-VMHost-LocationClusterName) { $esx| Get-VirtualSwitch-NamevSwitch1 | New-VirtualPortGroup-Name"VLAN500"-VlanId500 }# Backup each vNetwork Distributed Switch not including the port groupsexport-vdswitch$switch-Withoutportgroups-Description“Backup of $switchwithout port groups”-Destination“c:\vSphere\$switch.without_portgroups.$date.zip“# Backup each vNetwork Distributed Switch including the port groupsexport-vdswitch$switch-Description“Backup of $switchwith port groups”-Destination“c:\vSphere\$switch.with_portgroups.$date.zip“# Backup each port group individuallyget-vdswitch$switch| Get-VDPortgroup| foreach{ export-vdportgroup-vdportgroup$_-Description“Backup of port group $($_.name)”-destination“c:\vSphere\$($_.name).portgroup.$date.zip“}# Swing VMs from one port group to anotherget-vm| get-networkadapter| where-object{ $_.networkname -like"OldPortGroup"} | set-networkadapter-networkname"NewPortGroup"-Confirm:$false# vCenter# Gather vCenter LogonsGet-VIEvent-MaxSamples100000 | ?{($_-is[VMware.Vim.UserLoginSessionEvent]) -or($_-is[VMware.Vim.UserLogoutSessionEvent])} | %{if($_-is[VMware.Vim.UserLoginSessionEvent]) {  $strLoginOrLogout= "logged in"; $strSourceIP= $_.IpAddress}  else{  $strLoginOrLogout= "logged out"; $strSourceIP= $null  }New-Object-TypeNamePSObject-Property@{UserName = $_.UserNameSourceIP = $strSourceIPTime = $_.CreatedTimeAction = $strLoginOrLogout}} | Select UserName,SourceIP,Time,Action | 
 
No comments:
Post a Comment