Skip to content

Remove-Host

VMware: Removes the specified host from the inventory

#Requires -Version 5.1
#Requires -Modules VMware.VimAutomation.Core
[CmdletBinding(DefaultParameterSetName = "byName")]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$VIServer,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [pscredential]$VICredential,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [string]$ID,
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$Name
)
Process {
    $vmServer = $null
    try {
        $vmServer = Connect-VIServer -Server $VIServer -Credential $VICredential -ErrorAction Stop
        if ($PSCmdlet.ParameterSetName -eq "byID") {
            $vmHost = Get-VMHost -Server $vmServer -ID $ID -ErrorAction Stop
        }
        else {
            $vmHost = Get-VMHost -Server $vmServer -Name $Name -ErrorAction Stop
        }
        $hostName = $vmHost.Name
        $null = Remove-VMHost -VMHost $vmHost -Server $vmServer -Confirm:$false -ErrorAction Stop
        $output = [PSCustomObject]@{
            Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            Status    = "Success"
            Message   = "Host $hostName successfully removed"
        }
        Write-Output $output
    }
    catch { throw }
    finally { if ($null -ne $vmServer) { Disconnect-VIServer -Server $vmServer -Force -Confirm:$false -ErrorAction SilentlyContinue } }
}

IP address or DNS name of the vSphere server

PSCredential object for authenticating with the server

ID of the host to remove

Name of the host to remove

An interactive directory of PowerShell scripts.