Using PowerCLI to Install Software in a Guest VM

Share on:

I have been constantly trying to figure out the best way to deploy updated agents to some of our virtual desktops. It isnt a large environment so I have no need for SCCM or other deployment tools, but its big enough having to RDP to each VM was a pain. I finally decided to bang out a script, and surprised how well it works.

Pre-Requsites

Preparing to Execute the Script

The script is pretty straight forward, just need to define a few variables seen below and then you execute the script. I will walk you through the process.

This script assumes you have already launched PowerCLI and connected to the vCenter using Connect-VIServer

 1#Define Variables
 2Write-Host "Prompt For Guest Credentials" -ForegroundColor Yellow
 3$Cred = Get-Credential
 4$VMs = "VM1","VM2"
 5#$VMs = Get-VM VM* | Sort Name
 6
 7Foreach ($VMName in $VMs) {
 8  $VM = Get-VM $VMName
 9
10#Define file information. Include File Name, Parameters, Source and Destination
11  $File = "VMware-v4vdesktopagent-x86_64-6.2.0-3295266.exe"
12  $Param = "/s /v/qn REBOOT=Reallysuppress"
13  $SrcPath = "c:\"
14  $DstPath = "c:\temp\"
15  $Fullpath = $SrcPath + $File
16
17  Write-Host Copying $Fullpath to $VMName -ForegroundColor Cyan
18  Copy-VMGuestFile -VM $VM -Source $Fullpath -Destination $DstPath -LocalToGuest -GuestCredential $Cred -Force
19
20  #Define Install File Command
21  $Command = $DstPath + $File + $Param
22  #Define Delete File Command
23  $Command2 = "del " + $DstPath + $File
24
25  Write-Host Executing $Command within guest operating system of $VMName -ForegroundColor White
26  $Result = Invoke-VMScript -VM $VM  -ScriptText $Command -GuestCredential $Cred
27  $ExitCode = $Result.ExitCode
28  if ($ExitCode = "0") {
29    Write-Host $VMName returned exit code $ExitCode -ForegroundColor Green
30  }
31  Else {
32    Write-Host $VMName returned exit code $ExitCode -ForegroundColor Red
33  }
34  Write-Host Executing $Command2 within guest operating system of $VMName -ForegroundColor White
35  $Result2 = Invoke-VMScript -VM $VM  -ScriptText $Command2 -GuestCredential $Cred
36  $ExitCode2 = $Result2.ExitCode
37  if ($ExitCode2 = "0") {
38    Write-Host $VMName returned exit code $ExitCode2 -ForegroundColor Green
39  }
40  Else {
41    Write-Host $VMName returned exit code $ExitCode2 -ForegroundColor Red
42  }
43}

Execute the Script

  • Run .\InstallVMSoftware.ps1
comments powered by Disqus

See Also