SharePoint: Apply theme to SharePoint site using Powershell

Following powershell function can be used to apply theme to SharePoint site.


function Apply-SPTheme([string]$SiteUrl, [string]$webName, [string]$themeName)
{
    $site = new-object Microsoft.SharePoint.SPSite($SiteUrl)
    $web = $site.OpenWeb($webName)
    $theme = [Microsoft.SharePoint.Utilities.ThmxTheme]::Open($site,"_catalogs/theme/" + $themeName + ".thmx")
    $theme.ApplyTo($web,$false)
    $web.Update()
    $web.Dispose()
    $site.Dispose()
}


To apply the theme to site collection call the above function as follows:
Apply-SPTheme "http://intranet.contoso.com"  "" "Azure"


To apply the theme to subsite "XYZ" inside site collection call the above function as follows
Apply-SPTheme "http://intranet.contoso.com"  "XYZ" "Azure"