Some assumptions are made with the following statement which are not always true - eg. user email may be [email protected] however the onmicrosoft domain may be different, say companyxy.onmicrosoft.com and the SPO domain is based on this
[string] $TenantDomain = (ConvertTo-Domain $UserPrincipalName)
$domains = get-msoldomain ## get a list of all domains in tenant
foreach ($domain in $domains) { ## loop through all these domains
if ($domain.name.contains('onmicrosoft')) { ## find the onmicrosoft.com domain
$onname = $domain.name.split(".") ## split the onmicrosoft.com domain when found at the period. Will produce an array that contains each string as an element
$tenantname = $onname[0] ## the first string in this array is the name of the tenant
} ## end of find the on.microsoft.com domain
}