Converting onedrive url to UPN

Had a bit of a struggle converting onedrive for business url’s reliably to UPN’s.

Since a path might contain /personal/ multiple times, and we have those pesky national tenants with special url’s to deal with…

So thought I’d share:

function Get-UPNFromOnedriveUrl{
    Param(
        [string]$url
    )

    $userName = ''
    if ($url -match ':\/\/.*?\..*?\/personal\/(.*?)\/') {
        $userName = $matches[1]
    }else {
        Throw "Invalid OneDrive URL format: $url"
    }

    if(!$global:tenantODStyleDomains){
        $global:tenantODStyleDomains = New-GraphQuery -Uri "https://graph.microsoft.com/v1.0/domains" -Method GET -resource "https://graph.microsoft.com" | ForEach-Object { $_.id.replace(".","_") }
    }

    foreach($tenantODStyleDomain in $global:tenantODStyleDomains){
        if($userName -like "*_$tenantODStyleDomain"){
            $prefix = $userName.Replace("$tenantODStyleDomain","") 
            $suffix = $tenantODStyleDomain.Replace("_",".")
            break
        }
    }

    return "$prefix@$suffix".Replace("_","").ToLower()
}
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments