Hello,
I don't know if it has already asked.
I'm looking for something to check if some VMs exists , and are powered off ==> remove them and report.
If they do not exists or are still powered on, report it .
The idea is targeting several vcenters and get the VMs from a file. I have started something like that: but it is not my day. I would need some light from your side. Thank you
$vmList = Get-Content C:\temp\inputFile.txt -ErrorAction SilentlyContinue
foreach ($vmName in $vmList)
{
$foundvmm=get-vm $vmname| Select name
If ($foundvm) -And ($foundvm.PowerState -eq "PoweredOff")
{
write-host "$foundvm PoweredOff"
sleep 2
Remove-VM $foundvm -DeletePermanently -confirm:$false
write-host "$foundvm Removed"
sleep 2
else{ write-host "$foundvm not found or still powered on, please check and restart the decomm job process"}
}
You could do something like this
Get-Content C:\temp\inputFile.txt -ErrorAction SilentlyContinue -PipelineVariable row |
ForEach-Object -Process {
$vm = Get-VM -Name $row
if($vm -and $vm.PowerState -eq 'PoweredOff'){
Remove-VM -VM $vm -DeletePermanently -Confirm:$false
Write-Host "VM $row removed"
}
elseif($vm){
Write-Host "VM $row not powered off"
}
else{
Write-Host "VM $row not found"
}
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thank you , it is working... I'm looking to skip the not-found vm msg
Get-VM : 19/05/2021 10:25:29 Get-VM VM with name 'VMTESTX' was not found using the specified filter(s).
At line:3 char:9
+ $vm = Get-VM -Name $row
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-VM], VimException
+ FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM
Add -ErrorAction SilentlyContinue on the Get-VM.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference