Powershell: Mount Datastore ISO to Multiple VM’s

I had to install a piece of software on several vm’s a few days ago and got somewhat bored of the same repetitive task of mounting the ISO to all of the vm’s cd-rom drive. So, I wrote a script that will automatically mount the ISO that I specify and connect the cd-rom drive.

$VMs = (Get-Content servers.txt)
$ds = (Read-Host "Type the datastore name:")
$ISO_Path = (Read-Host "Type the path to the iso file:")

foreach($vm in $VMs){
	Get-CDDrive $vm | Set-CDDrive -StartConnected:$true -Connected:$true -IsoPath [$ds]  $ISO_Path -Confirm:$false
}

What this script does is prompt you for the datastore location that your ISO’s are located in. For example, if your ISO is located in the datastore “ISOs” you would type that. The script then prompts you for the full path to the iso. This is what your input should look like

1. Type the datastore name: vm_isos
2. Type the path to the iso file: folder/folder1/folder2/file.iso

On the flip side if you want to disconnect the cd-rom from multiple vm’s, you just need to modify the script a bit.

$VMs = (Get-Content servers.txt)

foreach($vm in $VMs){
	Get-CDDrive $vm | Set-CDDrive -NoMedia -StartConnected:$false 
-Connected:$false -Confirm:$false
}

Note: This will actually remove the mounted iso (-NoMedia) but it will also disconnect the cd-rom and set the startconnected switch to false.

Powershell: Shutdown VM and Delete From Disk

This is a fairly simple script but I thought I’d share. I needed to delete a group of about 6 virtual machines this morning. I could easily do this through the vSphere GUI but I figured I’d write a quick script so I could use it for future deletions.


$VMs = (Get-Content servers.txt)

foreach($vm in $VMs){
$active = Get-VM $vm
if($active.PowerState -eq "PoweredOn"){
Stop-VM -VM $vm -Confirm:$false
Start-Sleep -Seconds 10
Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync}
else
{Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync}
}

Updated Script:

$VMs = (Get-Content servers.txt)
$vmObj = Get-vm $vms

foreach($active in $vmObj){
if($active.PowerState -eq "PoweredOn"){
Stop-VM -VM $active -Confirm:$false -RunAsync | Out-Null} 
}
Start-Sleep -Seconds 7

foreach($delete in $vmObj){
Remove-VM -VM $delete -DeleteFromDisk -Confirm:$false -RunAsync | Out-Null}

This script will run a lot quicker and the code is a bit cleaner.