The script below gathers all VMs and disconnects the CDROM if its found to be connected:
$VMs = Get-VM
$CDConnected = Get-CDDrive $VMs
| where { ($_.ConnectionState.Connected -eq "true") -and ($_.ISOPath -notlike "*.ISO*")}
If ($CDConnected -ne
$null) {Set-CDDrive -connected 0 -StartConnected 0 $CDConnected -Confirm:$false }
How would you put this into a Foreach statement to gather all VMs in all Datacenters in all clusters and dismount/disconnect the CDROM if its found?
Something like this for example
foreach($VM in Get-VM){
$CDConnected = Get-CDDrive $VM |
where { ($_.ConnectionState.Connected -eq "true") -and ($_.ISOPath -notlike "*.ISO*")}
If ($CDConnected -ne $null) {
Set-CDDrive -CD $CDConnected -connected $false -StartConnected 0 -Confirm:$false
}
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Something like this for example
foreach($VM in Get-VM){
$CDConnected = Get-CDDrive $VM |
where { ($_.ConnectionState.Connected -eq "true") -and ($_.ISOPath -notlike "*.ISO*")}
If ($CDConnected -ne $null) {
Set-CDDrive -CD $CDConnected -connected $false -StartConnected 0 -Confirm:$false
}
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thank you! This worked with one datacenter, but will it work with multiple datacenters or do i need to nest a foreach statement with something like:
ForEach ($dc in Get-Datacenter){$dc | {$cluster in Get-Cluster...
foreach($VM in Get-VM){
$CDConnected = Get-CDDrive $VM |
where { ($_.ConnectionState.Connected -eq "true")}
If ($CDConnected -ne $null) {
Set-CDDrive -CD $CDConnected -connected $false -StartConnected 0 -Confirm:$false
}
Or is the one foreach statement sufficient? I dont have the resources to test multiple datacenters at the moment
If these Datacenters are all in the vCenter to which you are connected (check the content of $global:defaultviserver), you don't need the extra foreach loop.
The Get-VM will return all VMs in that vCenter, independent of which Datacenter they are in.le
If you have multiple vCenters, if you connect to all of them (check $global:defaultviservers), you still would only need the single foreach loop with the Get-VM.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference