if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole] "Administrator")) {
		Write-Output "Not elevated: relaunching as admin..."
		Start-Process -FilePath powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
		exit 1
}

if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
	write-warning "Y'arg Matey, we're off to 64-bit land....."
	if ($myInvocation.Line) {
		&"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile $myInvocation.Line
	}else{
		&"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -file "$($myInvocation.InvocationName)" $args
	}
	exit $LastExitCode
}

# cerca esattamente il device che vogliamo rimuovere (Nome + ServiceName)
$targetPNP = $null
try {
	$targetPNP = Get-CimInstance -ClassName Win32_NetworkAdapter -ErrorAction SilentlyContinue |
				Where-Object { $_.NetConnectionID -eq 'TAP-HT Portal' -and $_.ServiceName -eq 'tap0901' } |
				Select-Object -ExpandProperty PNPDeviceID -ErrorAction SilentlyContinue

	if (-not $targetPNP) {
			# prova 2: Get-PnpDevice (friendly name) -> InstanceId (richiede modulo PnpDevice presente)
			try {
				$p = Get-PnpDevice -FriendlyName 'TAP-HT Portal' -ErrorAction SilentlyContinue |
					Where-Object { $_.Class -ne $null } | Select-Object -ExpandProperty InstanceId -First 1
				if ($p) { $targetPNP = $p }
			} catch {
				# Get-PnpDevice puÃ² non essere disponibile in sistemi molto vecchi; ignoriamo l'errore
			}
	}

	if (-not $targetPNP) {
			# prova 3: usa Get-NetAdapter per ottenere InterfaceDescription e mappalo a Win32_NetworkAdapter
			$net = Get-NetAdapter -Name 'TAP-HT Portal' -ErrorAction SilentlyContinue
			if ($net) {
					$desc = $net.InterfaceDescription
					if ($desc) {
							$targetPNP = Get-CimInstance -ClassName Win32_NetworkAdapter -ErrorAction SilentlyContinue |
										Where-Object { ($_.Description -eq $desc -or $_.Name -eq $desc) -and $_.ServiceName -eq 'tap0901' } |
										Select-Object -ExpandProperty PNPDeviceID -ErrorAction SilentlyContinue
					}
			}
	}
} catch { $targetPNP = $null }

if ($targetPNP) {
	Write-Output "Found existing TAP-HT Portal: $targetPNP"
	$p = Start-Process -FilePath pnputil.exe -ArgumentList '/remove-device', $targetPNP -Wait -PassThru
	if ($p.ExitCode -ne 0) {
		Write-Warning "pnputil returned exit code $($p.ExitCode). Continuing (may require reboot)."
	} else {
		Write-Output "Device removed."
	}
} else {
	Write-Output "No existing TAP-HT Portal found. Nothing to do."
}

exit 0