Upload Master Page and Make It as a Default Master Page Using PowerShell in SharePoint

  1. Write-Host “Upload master page to Master Page Gallaery and make this master page is Default master page to site Operation creating” -ForegroundColor Yellow    
  2. Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue     
  3. $WebURL = Read-Host "Please enter your SiteCollection Url"    
  4.     
  5. $MasterPageName = "CRSMasterPage.master"    
  6. $SourcePath ="C:\scripts\MyMasterPage.master"    
  7.    
  8. #Get the Web    
  9. $web = Get-SPWeb $WebURL    
  10.    
  11. #Get the Target folder - Master page Gallery    
  12. $MasterPageList = $web.GetFolder("Master Page Gallery")    
  13.    
  14. #Set the Target file for Master page    
  15. $TargetPath = $Web.Url + "/_catalogs/masterpage/" + $MasterPageName    
  16.   
  17.   
  18.    
  19. #Get the Master page from local disk    
  20. $MasterPageFile = (Get-ChildItem $SourcePath).OpenRead()    
  21.    
  22.  #Check if file exist already    
  23.  if ($Web.GetFile($TargetPath).Exists)    
  24.   {    
  25.     $Web.GetFile($TargetPath).recycle()    
  26.   }    
  27.    
  28. #upload master page using powershell    
  29. $MasterPage = $MasterPageList.Files.Add($TargetPath,$MasterPageFile,$false)    
  30.   
  31.   
  32.         
  33. #Prepare the Custom Master page URL    
  34. $WebURL = $web.ServerRelativeUrl.TrimEnd("/")    
  35. $MasterPageURL = $WebURL+"/_catalogs/masterpage/" + $MasterPageName    
  36.    
  37. #Set Default and Custom Master pages    
  38. $web.MasterUrl = $MasterPageURL    
  39. $web.CustomMasterUrl = $MasterPageURL    
  40.    
  41. #Apply Changes    
  42. $MasterPage.Update()    
  43. $MasterPage.Publish("")    
  44. $web.Update()    
  45. $web.Dispose()    
  46. Write-Host “Add Default Master Page to Site Operation Completed Successfully” -ForegroundColor Yellow