# findGuestMvsByStorage.ps1
$storagePath='\\SMBSERVER009'
function getAllGuestVms($clusterName){
try{
Import-Module FailoverClusters
$clusterName=if($clusterName){
$clustername
}else{
(get-cluster).name
}
$allHyperVHosts={(Get-ClusterNode -Cluster $clusterName|?{ $_.State -eq "Up" }).Name | %{$_.ToLower()}}.Invoke()
$allVms=foreach ($hyperVHost in $allHyperVHosts){
invoke-command -computername $hyperVHost -scriptblock{
write-host "Getting VM List on $env:computername";
Get-VM |select-object Name,State,Status,Path
}|select-object * -ExcludeProperty RunspaceId,PSShowComputerName
}
if($allVms){return $allVms}else{return $null}
}catch{
write-warning $_
return $false
}
}
function findGuestMvsByStorage{
param (
$storagePath,
$clusterName=$null
)
try{
$allVms=getAllGuestVms $clusterName
if(!$allVms){return $null}
$matchedStorage=$allVms|?{$_.Path -like "*$storagePath*"}
$online=$matchedStorage|?{$_.State.Value -like 'Running*'}
$offline=$matchedStorage|?{$_.State.Value -notlike 'Running*'}
if($online){
write-host "There are $($online.count) online VMs associated with '$storagePath'"
}
if($offline){
write-host "There are $($offline.count) offlined VMs associated with '$storagePath'"
}
if($matchedStorage){
$matchedStorage
return $matchedStorage
}else{
write-host "'$storagePath' is not being associated with any VM in cluster '$((get-cluster).Name)'"
return $null
}
}catch{
write-warning $_
return $false
}
}
$result=findGuestMvsByStorage $storagePath
$result|select Name,State,PSComputerName
# Sample Output
PS C:\Windows\system32> $result=findGuestMvsByStorage $storagePath
Getting VM List on HYV01
Getting VM List on HYV02
Getting VM List on HYV03
Getting VM List on HYV04
Getting VM List on HYV05
Getting VM List on HYV06
Getting VM List on HYV07
Getting VM List on HYV08
Getting VM List on HYV09
Getting VM List on HYV10
Getting VM List on HYV11
Getting VM List on HYV12
Getting VM List on HYV13
Getting VM List on HYV14
Getting VM List on HYV15
Getting VM List on HYV16
Getting VM List on HYV17
Getting VM List on HYV18
Getting VM List on HYV19
There are 6 online VMs associated with '\\FILESERVER009'
There are 16 offlined VMs associated with '\\FILESERVER009'
PS C:\Windows\system32> $result|select Name,State
Name State
---- -----
TESTVM01 OffCritical
TESTVM02 Off
TESTVM03 OffCritical
TESTVM04 OffCritical
TESTVM05 RunningCritical
Categories: