-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVMrun.ps1
More file actions
477 lines (427 loc) · 32.3 KB
/
VMrun.ps1
File metadata and controls
477 lines (427 loc) · 32.3 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<#
.SYNOPSIS
Quick control commands for local VMware VMs
.DESCRIPTION
Uses the VMrun.exe executible from VMWare Workstation to perform quick management of local VMs
for example sending multiple poweron/poweroff commands to multiple VMs at once
.OUTPUTS
.NET GUI Managment dialog
.EXAMPLE
.\VMrun.ps1
# Locates VMrun.exe and Workstation config file (${env:ProgramData}\VMware\hostd\config.xml) and
# ($env:APPDATA\VMware\inventory.vmls) to control local VM inventory. No Parameters required
.NOTES
Created by Sadik Tekin
Gek-Tek Solutions Ltd
Requires VMware Workstation (http://www.vmware.com/products/workstation.html).
#>
# Check if run as Administrator
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
(new-object -ComObject wscript.shell).Popup("Please re-run as Administrator",0,"RunAs Admin")
Break
}
#net start vmx86 # On rare occasions may need to start this service after boot
# Find VMware Workstation install directory
$xml = [xml](Get-Content "${env:ProgramData}\VMware\hostd\config.xml")
if ($xml -eq $null)
{
(new-object -ComObject wscript.shell).Popup("Can't load Workstation config file:`n${env:ProgramData}\VMware\hostd\config.xml",0,"File not Found")
Break
}
else
{
$WP = $xml.config.defaultInstallPath
$WorkstationPath = $WP.Trim()
}
# Locate VMRun.exe
$vmRun = $WorkstationPath + "vmrun.exe"
if (-NOT (Test-Path $vmRun))
{
#throw [System.IO.FileNotFoundException] "$vmRun Needed"
(new-object -ComObject wscript.shell).Popup("Could not locate $vmRun",0,"File not Found")
Break
}
# If found create vmrun common alias
else { set-alias vmrun $vmRun }
# Check if user profile settings exist
$vmlsFile = "$env:APPDATA\VMware\inventory.vmls"
if (-NOT (Test-Path -path $vmlsFile))
{
#throw [System.IO.FileNotFoundException] "$vmlsFile Not Found"
(new-object -ComObject wscript.shell).Popup("Could not locate $vmlsFile",0,"File not Found")
Break
}
# Store content of VMware Workstation (Roaming) preferences into String
else { $Config = Get-Content $vmlsFile | Select-String -Pattern 'index[0-99]\.id' }
# Create the session logging feature
function Out2Log
{
[CmdletBinding()] Param(
[Parameter(Mandatory=$True)][string]$l_string,
[Parameter(Mandatory=$True)][int]$l_severity
)
# Message levels
$l_levels = @{0="[Alert] "; 1="[Info] "}
$DT = Get-Date -UFormat "%Y%m%d"
$l_fname = "VMrun-" + $DT + ".log"
$entryTime = (Get-Date).ToUniversalTime().ToString("HH:mm:ss.fff")
<# Write log to file
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
if (-NOT (Test-Path -path $ScriptPath\logs))
{ New-Item -ItemType directory -path $ScriptPath\logs\ | Out-Null }
$l_severity.ToString() + "`t" + `
$entryTime + " GMT`t" + `
$l_levels.Get_Item($l_severity) + `
$l_string | Out-File -Append -NoClobber -Encoding UTF8 -FilePath $ScriptPath\logs\$l_fname
#>
# Log to GUI Logbox
$entryTime + " GMT`t" + `
$l_levels.Get_Item($l_severity) + `
$l_string | ForEach-Object {[void] $objLogBox.Items.Add($_)}
# Autoscroll Listbox
$objLogBox.SelectedIndex = $objLogBox.Items.Count - 1;
$objLogBox.SelectedIndex = -1;
<# Autoscroll textbox:
$objLogBox.SelectionStart = $objLogBox.Text.Length;
$objLogBox.ScrollToCaret();
#>
}
#------------------------------
# Retrieve local VM paths using inventory.vmls
Function Get-VMPaths {
$Config | ForEach-Object {
$filePath = $_ -split ' = '
$filePath[1]
}
}
# Split VM paths to leave VM names only
Function Get-VMNames {
$VMPaths | ForEach-Object {
$fileName = $_ -split '([^\\]+$)' -replace '.vmx"',''
$fileName[1]
}
}
# Pass these into variables
$VMPaths = Get-VMPaths
$VMNames = Get-VMNames
#------------------------------
Function Start-VM
{
# Capture list of running VMs to an Array - skip the 1st entry
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
# Full path to VM in VMSelection needed
$VMselection |
ForEach-Object {
#check if selected vm ($objItem) is running by matching $RunningVMs
if (-NOT ($RunningVMs -match $objItem)){
Out2Log "Starting $objItem..." -l_severity 1
# execute VMrun expression to start VM
try { vmrun -T ws start $_ nogui }
# Catch any errors into log
catch { Out2Log ("Could not start $objItem " + $_) -l_severity 0 }
Out2Log "$objItem Started" -l_severity 1
}}
}
Function StartAll-VMs
{
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
# Use VMPaths to control all VMs
$VMPaths |
ForEach-Object {
# Skip RunningVMs by matching list from $VMPaths
if (-NOT ($RunningVMs -match $_)){
# Grab just VM name from path for logging
$item = $_ -split '([^\\]+$)' -replace '.vmx"',' '
Out2Log ("Starting " + $item[1] + "...") -l_severity 1
# execute VMrun expression to start VM if powered off
try { vmrun -T ws start $_ nogui }
catch { Out2Log ("Could not start " + $item[1] + $_) -l_severity 0 }
Out2Log ($item[1] + " Started") -l_severity 1
}}
}
Function Suspend-VM
{
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
$VMselection |
ForEach-Object {
if ($RunningVMs -match $objItem){
Out2Log "Suspending $objItem..." -l_severity 1
try { vmrun -T ws suspend $_ nogui }
catch { Out2Log ("Could not Suspend $objItem " + $_) -l_severity 0 }
Out2Log "$objItem Suspended" -l_severity 1
}}
}
Function SuspendAll-VMs
{
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
$RunningVMs |
ForEach-Object{
$item = $_ -split '([^\\]+$)' -replace '.vmx',' '
Out2Log ("Suspending " + $item[1] +"...") -l_severity 1
try { vmrun -T ws suspend $_ nogui}
catch { Out2Log ("Error while Suspending " + $item[1] + $_) -l_severity 0 }
Out2Log ($item[1] + "Suspended") -l_severity 1
}
}
Function Reset-VM
{
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
$VMselection |
ForEach-Object {
if ($RunningVMs -match $objItem){
Out2Log ("Resetting $objItem...") -l_severity 1
try { vmrun -T ws reset $_ soft nogui }
catch { Out2Log ("Could not SOFT Reset $objItem, ensure VM tools are installed " + $_) -l_severity 0 }
Out2Log ("$objItem Restarted") -l_severity 1
}}
}
Function Stop-VM
{
$RunningVMs = Invoke-Expression "vmrun list" | Select-Object -skip 1
$VMselection |
ForEach-Object {
if ($RunningVMs -match $objItem){
Out2Log ("Powering off $objItem...") -l_severity 1
try { vmrun -T ws stop $_ soft nogui }
catch { Out2Log ("Could not SOFT Stop $objItem, ensure VM tools are installed " + $_) -l_severity 0 }
Out2Log ("$objItem Stopped") -l_severity 1
}}
}
Function CreateSnapshot
{
$VMselection |
ForEach-Object {
Out2Log ("Creating Snapshot for $objItem...") -l_severity 1
$DT2 = (Get-Date -Format "s") -replace "T"," @ "
$snapshotname = $DT2
try { vmrun -T ws snapshot $_ $snapshotname }
catch { Out2Log ("Could not create Snapshot for $objItem " + $_) -l_severity 0 }
Out2Log ("$objItem [$snapshotname] Created") -l_severity 1
}
}
#Create GUI
$x = @()
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "VMrun GUI"
$objForm.Size = New-Object System.Drawing.Size(375,500)
$objForm.StartPosition = "CenterScreen"
try {
$icon = [system.drawing.icon]::ExtractAssociatedIcon("$WorkstationPath\vmware.exe")
$objForm.Icon = $icon
} catch { Out2Log ("Error retrieving app icon: " + $_) -l_severity 0 }
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Enter")
{
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match "$_"; Start-VM }
}
}
})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
$tooltip = New-Object System.Windows.Forms.ToolTip
$ShowHelp={
#display popup help
#each value is the name of a control on the form.
Switch ($this.name) {
"StartVM" {$tip = "PowerOn Multiple VMs"}
"StartAll" {$tip = "PowerOn All VMs"}
"StopVM" {$tip = "PowerOff Multiple VMs"}
"SuspendVM" {$tip = "Suspend Multiple VMs"}
"SuspendAll" {$tip = "Suspend All VMs"}
"ResetVM" {$tip = "Perform Soft Reset on Multiple VMs"}
"Snapshot" {$tip = "Create a Snapshot of Selected VMs"}
"PuttyButton" {$tip = "Launch Putty"}
"NetConfigButton" {$tip = "Launch Network Config Editor"}
"Git" {$tip = "Visit the GitHub Repo"}
}
$tooltip.SetToolTip($this,$tip)
} #end ShowHelp
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Size(10,180)
$StartButton.Size = New-Object System.Drawing.Size(75,23)
$StartButton.Text = "Start"
$StartButton.Name = "StartVM"
$StartButton.add_MouseHover($ShowHelp)
$StartButton.Add_Click({
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match "$_"; Start-VM }
}
})
$objForm.Controls.Add($StartButton)
$StartAllButton = New-Object System.Windows.Forms.Button
$StartAllButton.Location = New-Object System.Drawing.Size(10,210)
$StartAllButton.Size = New-Object System.Drawing.Size(75,23)
$StartAllButton.Text = "Start All"
$StartAllButton.Name = "StartAll"
$StartAllButton.add_MouseHover($ShowHelp)
$StartAllButton.Add_Click(
{
$Confrim = [System.Windows.Forms.MessageBox]::Show("Start/Resume all VMs?" , "Start ALL" , 4)
if ($Confrim -eq "YES" ) { StartAll-VMs }
})
$objForm.Controls.Add($StartAllButton)
$SuspendButton = New-Object System.Windows.Forms.Button
$SuspendButton.Location = New-Object System.Drawing.Size(90,180)
$SuspendButton.Size = New-Object System.Drawing.Size(75,23)
$SuspendButton.Text = "Suspend"
$SuspendButton.Name = "SuspendVM"
$SuspendButton.add_MouseHover($ShowHelp)
$SuspendButton.Add_Click({
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match $_; Suspend-VM }
}
})
$objForm.Controls.Add($SuspendButton)
$SuspendAllButton = New-Object System.Windows.Forms.Button
$SuspendAllButton.Location = New-Object System.Drawing.Size(90,210)
$SuspendAllButton.Size = New-Object System.Drawing.Size(75,23)
$SuspendAllButton.Text = "Suspend All"
$SuspendAllButton.Name = "SuspendAll"
$SuspendAllButton.add_MouseHover($ShowHelp)
$SuspendAllButton.Add_Click(
{
$Confrim = [System.Windows.Forms.MessageBox]::Show("Suspend all VMs?" , "Suspend ALL" , 4)
if ($Confrim -eq "YES" ) { SuspendAll-VMs }
})
$objForm.Controls.Add($SuspendAllButton)
$ResetButton = New-Object System.Windows.Forms.Button
$ResetButton.Location = New-Object System.Drawing.Size(10,240)
$ResetButton.Size = New-Object System.Drawing.Size(75,23)
$ResetButton.Text = "Reset"
$ResetButton.Name = "ResetVM"
$ResetButton.add_MouseHover($ShowHelp)
$ResetButton.Add_Click(
{
$Confrim = [System.Windows.Forms.MessageBox]::Show("(Soft) Reset the selected VMs?" , "Reset" , 4)
if ($Confrim -eq "YES" )
{
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match "$_"; Reset-VM }
}
}
})
$objForm.Controls.Add($ResetButton)
$StopButton = New-Object System.Windows.Forms.Button
$StopButton.Location = New-Object System.Drawing.Size(90,240)
$StopButton.Size = New-Object System.Drawing.Size(75,23)
$StopButton.Text = "Stop"
$StopButton.Name = "StopVM"
$StopButton.add_MouseHover($ShowHelp)
$StopButton.Add_Click({
$Confrim = [System.Windows.Forms.MessageBox]::Show("Shutdown selected VMs?" , "Shutdown" , 4)
if ($Confrim -eq "YES" )
{
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match "$_"; Stop-VM }
}
}
})
$objForm.Controls.Add($StopButton)
$SnapshotButton = New-Object System.Windows.Forms.Button
$SnapshotButton.Location = New-Object System.Drawing.Size(270,180)
$SnapshotButton.Size = New-Object System.Drawing.Size(75,23)
$SnapshotButton.Text = "Snapshot"
$SnapshotButton.Name = "Snapshot"
$SnapshotButton.add_MouseHover($ShowHelp)
$SnapshotButton.Add_Click({
$Confrim = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to Snaphot the selected VMs?" , "Create Snapshots" , 4)
if ($Confrim -eq "YES" )
{
foreach ($objItem in $objListbox.SelectedItems)
{
$x += $objItem
$objItem | ForEach-Object { $VMselection = $VMPaths -match "$_"; CreateSnapshot }
}
}
})
$objForm.Controls.Add($SnapshotButton)
$NetConfigButton = New-Object System.Windows.Forms.Button
$NetConfigButton.Location = New-Object System.Drawing.Size(300,220)
$NetConfigButton.Size = New-Object System.Drawing.Size(45,45)
$NetConfigButton.Name = "NetConfigButton"
$NetConfigButton.add_MouseHover($ShowHelp)
try {
$NetConfigicon = [system.drawing.icon]::ExtractAssociatedIcon("$WorkstationPath\vmnetcfg.exe")
$NetConfigButton.Image = $NetConfigicon
} catch { $NetConfigButton.Text = "VMNet" }
$NetConfigButton.Add_Click(
{
# Start NMnet editor as admin
try { Start-Process "$WorkstationPath\vmnetcfg.exe" -Verb RunAs }
catch { Out2Log ("Failed to launch Virtual Network Editior: " + $_) -l_severity 0 }
})
$objForm.Controls.Add($NetConfigButton)
$PuttyButton = New-Object System.Windows.Forms.Button
$PuttyButton.Location = New-Object System.Drawing.Size(300,80)
$PuttyButton.Size = New-Object System.Drawing.Size(45,45)
$PuttyButton.Name = "PuttyButton"
$PuttyButton.add_MouseHover($ShowHelp)
try {
$puttyicon = [system.drawing.icon]::ExtractAssociatedIcon("$env:ProgramFiles\PuTTY\putty.exe")
$PuttyButton.Image = $puttyicon
} catch { $PuttyButton.Text = "Putty" }
$PuttyButton.Add_Click(
{
# Launch Putty SSH
try { [system.Diagnostics.Process]::start("putty.exe") }
catch { Out2Log ("Failed to launch Putty: " + $_) -l_severity 0 }
})
$objForm.Controls.Add($PuttyButton)
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please select the VM(s) you wish to control:"
$objForm.Controls.Add($objLabel)
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(10,40)
$objListBox.Size = New-Object System.Drawing.Size(285,100)
$objListbox.Height = 140
$objListBox.Sorted = $True
$objListBox.HorizontalScrollbar = $true
$objListbox.SelectionMode = "MultiExtended"
$objLogLabel = New-Object System.Windows.Forms.Label
$objLogLabel.Location = New-Object System.Drawing.Size(10,270)
$objLogLabel.Size = New-Object System.Drawing.Size(280,20)
$objLogLabel.Text = "Session Log:"
$objForm.Controls.Add($objLogLabel)
$objLogBox = New-Object System.Windows.Forms.ListBox
$objLogBox.Location = New-Object System.Drawing.Size(10,290)
$objLogBox.Size = New-Object System.Drawing.Size(335,100)
$objLogBox.Height = 150
$objLogBox.HorizontalScrollbar = $true
$objLogBox.SelectionMode = "MultiExtended"
$objForm.Controls.Add($objLogBox)
$GitLink = New-Object System.Windows.Forms.LinkLabel
$GitLink.Location = New-Object System.Drawing.Size(10,445)
$GitLink.Size = New-Object System.Drawing.Size(280,20)
$GitLink.LinkColor = "BLUE"
$GitLink.ActiveLinkColor = "RED"
$GitLink.Text = "GitHub"
$GitLink.Name = "Git"
$GitLink.add_MouseHover($ShowHelp)
$GitLink.add_Click({[system.Diagnostics.Process]::start("https://github.com/SuDT/VMRun")})
$objForm.Controls.Add($GitLink)
# add VM names to multi-select listbox
$VMNames | ForEach-Object {[void] $objListBox.Items.Add($_)}
$objForm.Controls.Add($objListbox)
#$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
# display GUI
$x