Functions/Remove-VMAndDestroyData.ps1


function Remove-VMAndDestroyData {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ArgumentCompleter( {
                param ( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters )
                Get-VM "$wordToComplete*" | Sort-Object Name | ForEach-Object { "`"$($_.Name)`"" }
            })]
        [string[]]
        $VMName
    )

    # $VMName = $Name

    $VMs = Get-VM $VMName -ErrorAction 0 -Verbose | Select-Object *


    if ($VMs) {

        foreach ($VM in $VMs) {
            if ($VM.Path -notlike "*$($VM.Name)") {

                Write-Host "VM: $($VM.Name) - $($VM.Path) is geen eigen folder"

            }
            else {

                $VMHDDs = (Get-VMHardDiskDrive -VMName $VMName).Path

                Stop-VM $VMName -TurnOff -Force -Verbose

                Remove-VM $VMName -Force -Verbose

                foreach ($hdd in $VMHDDs) {
                    if ($hdd) {
                        Remove-Item $hdd -Force -Verbose
                    }
                }

                Remove-Item $VM.Path -Recurse -Force -Verbose

            }
        }
    }
    else {
        "No such VM found"
    }
}