PowerShell/PowerCLI: UMount All ISOs At Once

#****************************************************************
# Script Name : UMount-ISOsfromAllVMs.ps1
# Purpose    : Enumerate and remove all CDROM mounted ISOs from 
#              VMs in every VCenter
# Date       : 12-20-2023 1735 CST
# - Initial version
# Author     : www.Burwell.tech, with the help of BingAI
#****************************************************************
'UMount-ISOsfromAllVMs.ps1'
'When ready remove "-WhatIf" from the end of the Get-VM line'
Set-ExecutionPolicy RemoteSigned -Force|Out-Null
# get-executionpolicy -Verbose #<-- to use to confirm

# Set variable for credential option and store for using in PowerShell scripts over and over
# You can use this code in your profile to call $PSCredential_VMWARE from any script too
# rm -Confirm "$env:USERPROFILE\localvmcredential.xml" <-- when you to reset the password stored
$localvmcredFile = "$env:USERPROFILE\localvmcredential.xml"  
  
if(Test-Path $localvmcredFile){  
    $PSCredential_VMWARE = Import-Clixml $localvmcredFile  
}  
else{  
    $localvmusername = "administrator@vsphere.local"
    $PSCredential_VMWARE = Get-Credential -Credential "$localvmusername"  
    $PSCredential_VMWARE | Export-Clixml $localvmcredFile  
}
# Get list of VCenters
$VIServers = @(
    "vcenter1.burwell.tech",
    "vcenter2.burwell.tech",
    "lab.burwell.tech"
)

foreach($VIServer in $VIServers){
param($PSCredential_VMWARE)
Connect-VIServer -Server $VIServer -credential $PSCredential_VMWARE -Verbose:$false |Out-Null
param($VIServer)
$Vms = Get-VM -Server $VIServer | Get-CDDrive | Where-Object {$_.IsoPath} | Select-Object Parent, IsoPath
$vmsCount = $Vms.Parent.Name.count
Write-host "There are $vmsCount VMs with VCenter mounted CDROM ISOs in $VIServer"
foreach ($vm in $Vms.Parent.Name ){
Get-VM -Name $vm | Get-CDDrive | Set-CDDrive -NoMedia -StartConnected $false -WhatIf #Remove this WhatIf when ready
}
}

Write-host "You are connected to these VIServers:"
$global:DefaultVIServers
Disconnect-VIServer $global:DefaultVIServers -Force -Confirm:$false -Verbose <#<--use to disconnect all at once when done#>

Posted

in

,

by