Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Tuesday, 25 May 2021

Add & Remove App Catalog SharePoint Online Site Collection



#Login with Global Admin id and update the email address below

Connect-SPOService -Url https://xxx-admin.sharepoint.com -credential {user}@xxx.com

# get a reference to the site collection where the site collection app catalog should be created

$site = Get-SPOSite https://xxx.sharepoint.com/sites/yyy/ 

# remove site collection app catalog

Remove-SPOSiteCollectionAppCatalog -Site $site

# Add site collection app catalog

Add-SPOSiteCollectionAppCatalog -Site $site


Note : Account used to create App Catalog Site Collection, must be Site Collection Administrators on both the tenant-level App Catalog and the target Site Collection


Saturday, 24 September 2016

Update or Change Service Account Password using PowerShell

SharePoint 2013 SP Managed Account:-

- Service accounts are accounts in Active Directory or you local system that are used by a Service (example: running the SQL Server Agent, Running the Search Crawler).
- Managed accounts are Service Accounts in Active Directory or your local system that are managed by SharePoint (example: automatic password management).
The difference between them is that the Managed Accounts are managed by SharePoint, while a regular Service account is not managed by SharePoint.

Get-SPManagedAccount

Retrieves accounts registered in the configuration database.
Syntax:-
Get-SPManagedAccount

Set-SPManagedAccount

Configures the managed account.

There are many ways we can change or update the Service account password.
- Open the server with service account.
- press "Ctr + Alt + Del" and change the password.
- After updated the password run the below script.
or Change the password through AD Service directly.

Syntax:-
$password=ConvertTo-SecureString -String $Encrypted -AsPlainText -Force
$m = Get-SPManagedAccount -Identity "DOMAINx\UserY"
Set-SPManagedAccount -Identity $m - ExistingPassword $password -UseExistingPassword $True

Saturday, 23 July 2016

Set SharePoint Custom Access Denied Page

Using Set-SPCustomLayoutsPage command you can set the custom access denied page.
Following are the steps:-
  •      Log into one of the farm WFEs as a farm administrator.
  •      Open Windows Explorer, and then navigate to this folder:-C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\
  •      Add a subfolder to this folder, naming it CustomPages.
  •      In the LAYOUTS folder copy the file AccessDenied.ASPX into the CustomPages subfolder, renaming it AccessDeniedNew.ASPX.
  •      Modify AccessDeniedNew.ASPX as desired.  To add text or other HTML elements to this page, be sure to introduce them within asp:Content tags. In the example below, formatted text has been added so that it will appear just below the "Sorry, this site..." message.
  •      After completing the modification on this WFE, copy the CustomPages subfolder into the LAYOUTS folder of each of the WFEs in your farm.
  •     Execute the command that will update the farm configuration database to point to the new location of the AccessDenied page: 
Set-SPCustomLayoutsPage -Identity "AccessDenied" -RelativePath "/_layouts/15/custompages/AccessDeniedNew.aspx" -WebApplication "http:/mywebapplication/"
  • The Access Denied page path is now updated.
  • Perform the IIS Reset activities in all the servers.

List of all users alerts in SharePoint 2013

Get the site collection level users alerts:-

 Add-PSSnapin microsoft.sharepoint.powershell
 $site = Get-SPSite "http://test/sites/spalerts/"
 $alertResultsCollection = @()
 foreach ($web in $site.AllWebs) {  
     foreach ($alert in $web.Alerts){
         $alertURL = $web.URL + "/" + $alert.ListUrl
         $alertResult = New-Object PSObject
         $alertResult | Add-Member -type NoteProperty -name "List URL" -value $alertURL
         $alertResult | Add-Member -type NoteProperty -name "Alert Title" -value $alert.Title
         $alertResult | Add-Member -type NoteProperty -name "Alert Type" -value $alert.AlertType
         $alertResult | Add-Member -type NoteProperty -name "Subscribed User"-value $alert.User
         $alertResultsCollection += $alertResult
      }
  }
  $site.Dispose()
  $alertResultsCollection
  
  ## Export to CSV
  $alertResultsCollection | Export-CSV "Alerts.csv"

Thursday, 7 January 2016

Delete all SharePoint Groups for list level using PowerShell

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$web = Get-SPWeb http://site-name/Inst/site
$list = $web.Lists.TryGetList("Deleted Documents")
if($list.HasUniqueRoleAssignments -eq $False)
{
$list.BreakRoleInheritance($True)
}
[Microsoft.SharePoint.SPRoleAssignmentCollection] $spRoleAssignments=$list.RoleAssignments

for([int] $a=$spRoleAssignments.Count-1; $a -ge 0;$a--)
{
$spRoleAssignments.Remove($a);
}
$web.Dispose()

Tuesday, 24 February 2015

Run reusable workflow for all list Items in SharePoint using PowerShell

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
# URL of the Site
$web = Get-SPWeb -Identity https://sharepointsrv/site1
$manager = $web.Site.WorkFlowManager
# Name of the list
$list = $web.Lists["Shared Documents"]
# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName("On Item Created","en-US")
$data = $assoc.AssociationData
$items = $list.Items
foreach($item in $items) {
        $wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
}
$manager.Dispose()
$web.Dispose()

Saturday, 21 February 2015

Update SharePoint list or library view using PowerShell

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$GetAllWebDetails = "D:\[Location]\GetAllWebDetails.csv"
#---------------Please do not delete-------
Start-SPAssignment -Global #Start Assignment for disposal
$Time=Get-Date
Write-Host Start Time:$Time -ForegroundColor Yellow `n
$ListNameStore=@("Management","ABC","123")
function UpdateViews($webUrl)
{
    $web = Get-SPWeb -Identity $webUrl
    Write-Host $web.Url
    $webLists = $web.Lists
    for ($i = 0; $i -lt $webLists.Count; $i++)
    {
        $list = $web.Lists[$i];
        foreach($stlist in $ListNameStore) {
            if($list.Title -eq $stlist ) {
          
                $column = $list.Fields["Column Name"]
                if($column -ne $null){  
                    $column.Hidden = $false  
                    $column.ReadOnlyField = $false  
                    $column.Update()
                    $list.Fields.Delete($column) 
                    $list.Update()
                }
              }
          }
    }
   
    $Web.Dispose()
}

IMPORT-CSV $GetAllWebDetails |
  ForEach-Object {
    $WebUrl=$_.WebUrl
      Write-Host  Update Views is Started in $WebUrl -ForegroundColor Green 
    $site = Get-SPSite $WebUrl
    foreach($web in $site.AllWebs){
        UpdateViews  $web.Url
    }
    Write-Host  Update Views is completed in $WebUrl -ForegroundColor Green
}
$EndTime = Get-Date
Write-Host `n End Time:$EndTime -ForegroundColor Yellow

Attach Lookup Columns to document and document set content types using PowerShell

Below is the PowerShell code for adding user in Attach Lookups To Document And DocSet Content Types.
- Need to change some configure details in script.
- Need to chagne in CSV file like ContentType, SiteColumn and ColumnSetting.


Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
Function CheckColumnExistsOnContentType{
Param($ContentType, $ColumnName)      
$Fields = $ContentType.Fields | ? {$_.InternalName -eq $ColumnName}
Write-Host $ColumnName $Fields
If($Fields -eq $Null){
Return $false
}
Else{
Return $true}      
}
 
    $SPSite = Get-SPSite -Identity http://serverName/
    $Web = $SPSite.RootWeb
    $Create = Import-Csv -path "C:\[location]\AttachLookupsToDocumentAndDocSetContentTypes.csv"
$Create
    ForEach($Row in $Create){
        $CT = $Web.ContentTypes[$Row.ContentType];
        $FieldAdd = $Web.Fields.GetFieldByInternalName($Row.SiteColumn)
  $ColumnExists = CheckColumnExistsOnContentType -ContentType $CT -ColumnName $FieldAdd
  if($ColumnExists -eq $True)
  {
   Write-Host "Attached Column" $FieldAdd.InternalName "to" $CT.name -ForegroundColor Cyan
   $FieldLink = New-Object Microsoft.SharePoint.SPFieldLink($FieldAdd)
   If($($_.'ColumnSetting') -eq "Hidden"){
    $FieldLink.Required = $false
    $FieldLink.Hidden = $true
   }
   ElseIf(($($_.'ColumnSetting') -eq "Required")){
        $FieldLink.Required = $true
   }
   Else{
       $FieldLink.Required = $false
   }
   $CT.FieldLinks.Add($FieldLink)
   $CT.Update($true)
   $Web.Update()
   $Web.Dispose()
   Write-Host " Column is added in Content Type" -ForegroundColor Green
  }
}

Flush Blob Cache in SharePoint 2013

Running in all the servers.


Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$webApp = Get-SPWebApplication http://ServerName.com
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
Write-Host "Flushed the BLOB cache for:" $webApp

Wednesday, 20 August 2014

Add users to SharePoint group using PowerShell to csv file

Below is the PowerShell code for adding user in SharePoint Group.

- Need to change some configure details in script.
- Need to chagne in CSV file like GroupName and UserID 

 
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue #Load Module
#Setvariable
#set the web application name
$varWebUrl="http://server-name/site/test/"
#set the CSV location, CSV format is [columnName(GroupName), columnName(UserID).
$varCSVLocation="C:\UserToUploadSharePointGroup\UserToUpload.csv"
#set the Log file location, where user details are save if not abel to add
$varLogFile="C:\UserToUploadSharePointGroup\UserNotAddedList.txt"
#------------------------------------------------------
$web = Get-SPWeb $varWebUrl
$count=1
$Time=Get-Date
Write-Host Start Time:$Time -ForegroundColor Yellow `n
# Import the .csv file, and specify manually the headers, without column name in the file
IMPORT-CSV $varCSVLocation |
  ForEach-Object {
    $group=$_.GroupName
    $user=$_.UserID
    $groupName = $web.SiteGroups[$group]
    Try
    {
        $user = $web.Site.RootWeb.EnsureUser($user)
        $groupName.AddUser($user)
        Write-Host -ForegroundColor green  ID:$count `t $user `t Users Added Successfully. 
    }
    Catch [system.exception]
    {
        Write-Host -ForegroundColor Red ID:$count `t $user `t Users is not added.
        $output= "ID:$count" +"  User: " +$user
        $output | Out-file $varLogFile -Append
    }
    $count=$count+1
  }
 $Web.Dispose()
 $EndTime = Get-Date
 Write-Host `n End Time:$EndTime -ForegroundColor Yellow
 

Thursday, 7 August 2014

Content type subscriber timer job recreate in sharePoint 2013 for Web Application level

Issue/Problem: - Due to some unknown issue we are not able to find out the OOB publishing content job for a particular web application. We are performing many option to recreate the job but not able to recreate the Out of box "Content Type Subscriber" timer job in web application level.

Resolve: - Run the PowerShell script for Disable and Enable the “Content Type Subscriber” job. Feature is activated when the web app is created. However, something is causing the timer job to not get created. You can run these two PowerShell commands to re-create the timer job. Change the URL to yours

Below is the following script:-

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue #Load Module
# Disables the feature because it's still running in the background when the web app was created.
Disable-SPFeature -Identity ContentTypeSyndication -Url http://webappurl.contoso.com -Confirm:$false

# Enables the feature which will show up on the Timer Job Definitions
Enable-SPFeature -Identity ContentTypeSyndication -Url http://webappurl.contoso.com

Tuesday, 29 July 2014

SharePoint Farm BackUp


Config DB backup can be accomplish by two ways through PS as below:

 - Full Config Back up of DB:
    Backup-SPConfigurationDatabase -Directory -DatabaseServer  -DatabaseName -Verbose
 - Configuration details alone
    Backup-SPFarm -Directory \\file_server\share\Backup -BackupMethod full -ConfigurationOnly

Full Farm Backup


    Backup-SPFarm – Directory “\\server_name\Full_Farm_Backup” –backupmethod Full

Monday, 14 July 2014

Set Index column in list in SharePoint 2013 using PowerShell


Following is the code
********************************************************
Start-SPAssignment
$subsite = Get-SPWeb http://perimeter.portal.qc.atc.local/apps/mngr

Function removeIndex ()
{
Param ($list,$InternalFldName)

    try
        {
        Write-Output "The searching  field $InternalFldName";

        $fldToIndex =$list.Fields.GetFieldByInternalName($InternalFldName);                                                

        Write-Output "The field $fldToIndex has been found";

            try
            {
               $index= $list.FieldIndexes.Item($fldToIndex.Id)
               $fldToIndex.Indexed = $true;  
               $list.FieldIndexes.Delete($fldToIndex.Id);
               Write-Output ("The indexed {0} has been removed" -f $fldToIndex.Title) ;
             
            }
            catch
            {
               Write-Output "The field $fldToIndex is already non-indexed"
            }

        }
    catch
        {
         $error[0]
        }

}


Function AddIndex ()
{
Param ($list,$InternalFldName)

    try
        {
        Write-Output "The searching  field $InternalFldName";

        $fldToIndex =$list.Fields.GetFieldByInternalName($InternalFldName);                                                

        Write-Output "The field $fldToIndex has been found";

            try
            {
               $index= $list.FieldIndexes.Item($fldToIndex.Id)
               Write-Output "The field $fldToIndex is already indexed"
            }
            catch
            {
                $fldToIndex.Indexed = $true;  
                $list.FieldIndexes.Add($fldToIndex);
                Write-Output ("The field {0} has been indexed" -f  $fldToIndex.Title);
            }

        }
    catch
        {
         $error[0]
        }

}

$listsToIndex = @{
"apps/mngr/lists/IMDocument"="Mngr_Id";
}

foreach ($lstToIndex in $listsToIndex.GetEnumerator())
{

Write-Output ( "Index  {0} for list {1} ..." -f $lstToIndex.Value,  $lstToIndex.Key );


$lst = $subsite.GetList($lstToIndex.Key)
$InternalFldName=$lstToIndex.Value

if (($lst -ne $null) -and ($InternalFldName -ne $null))
{
    #removeIndex  $lst $InternalFldName
    addIndex $lst $InternalFldName
    write-Output "~~~~~~~~~~~~~~~~~~~~"
 }
else
{
    Write-Output "The predefined list has error for $lst"
}

}

Saturday, 5 April 2014

Add Terms in Term Set in Sharepoint 2013 Managed Metadata Service Application using Powershell

Below code for add terms in term set in SharePoint 2013 using Power Shell Script.


function ImportTermSet([Microsoft.SharePoint.Taxonomy.TermStore]$store, [string]$groupName, [PSCustomObject]$termSet) {  
  function ImportTerm([Microsoft.SharePoint.Taxonomy.Group]$group, 
                      [Microsoft.SharePoint.Taxonomy.TermSet]$set, 
                      [Microsoft.SharePoint.Taxonomy.Term]$parent, 
                      [string[]]$path) {        
    if ($path.Length -eq 0) {
      return
    } elseif ($group -eq $null) {
      $group = $store.Groups | where { $_.Name -eq $path[0] }
      if ($group -eq $null) {
        $group = $store.CreateGroup($path[0])
      }
    } elseif ($set -eq $null) {
      $set = $group.TermSets | where { $_.Name -eq $path[0] }
      if ($set -eq $null) {
 Write-Host “Create $path[0]“
        $set = $group.CreateTermSet($path[0])
Write-Host “Created $path[0]“ 
      }
    } else {
      $node = if ($parent -eq $null) { $set } else { $parent }
      $parent = $node.Terms | where { $_.Name -eq $path[0] }       
      if ($parent -eq $null) {
        $parent = $node.CreateTerm($path[0], 1033)
      } 
    }
    
    ImportTerm $group $set $parent $path[1..($path.Length)]                                     
  }
  
  $termSetName = $termSet[0].”Term Set Name”    
  $termSet | where { $_.”Level 1 Term” -ne “” } | foreach {
    $path = @($groupName, $termSetName) + @(for ($i = 1; $i -le 7; $i++) { 
      $term = $_.”Level $i Term”
        if ($term -eq “”) {
          break
        } else {
          $term
        }
      }
    )
        
    ImportTerm -path $path
  }
}

$url = “http://vlad.test.loc”

$session = Get-SPTaxonomySession -Site $url
$store = $session.TermStores["Test - Managed Metadata Service Application"] 
$folder= Get-ChildItem -Path C:\Termset\ -Recurse -Include *.csv
$folder | ForEach-Object {
$FileName ="C:\Termset\"+$_.Name
$termSet = Import-Csv $FileName
ImportTermSet $store "Test Term Sets" $termSet
}
$store.CommitAll() 



Thursday, 20 February 2014

Custom and OOB Web Part details in one or more site collection in SharePoint

Create one CSV file with site collection url detials in "SiteCollectionName" columns.

Below is the power shell script to fetch the web part detials in Power Shell Grid View


if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
function enumerateWebParts($Url) {
    $site = new-object Microsoft.SharePoint.SPSite $Url   
                foreach($web in $site.AllWebs)
                {
        if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web))
                                {
            $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
            $pages = $pWeb.PagesList
            foreach ($item in $pages.Items)
                                                {
                $fileUrl = $webUrl +"/" + $item.File.Url
                $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
                $wps = $manager.webparts
                $wps | select-object @{Expression={$pWeb.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label="Type"}
            }
        }
        else {
            $pages = $null
            $pages = $web.Lists["Site Pages"]           
                                                if ($pages)
                                                {               
                                                foreach ($item in $pages.Items)
                                                {
                    $fileUrl = $webUrl +"/" + $item.File.Url
                    $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
                    $wps = $manager.webparts
                    $wps | select-object @{Expression={$pWeb.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label="Type"}
                }
            }
            else {
            }
        }        Write-Host"… completed processing" $web
    }
}

#Get the CSV file and connect to the SharePoint list
$vessellist = import-csv -Path "C:\SiteCollectionName.csv"
$itemCount = $vessellist.Count;
$currentItem = 1;
foreach($item in $vessellist)
{
    #Update the progress information
    Write-Progress -Id 1 -ParentId 0 -Activity "Listing Data In CSV File" -PercentComplete (($currentItem/$itemCount)*100) -Status "Item $currentItem or $itemCount";
    $currentItem++;
    #Write the rows VESSEL_NAME column to the console
                $row += enumerateWebParts($item.SiteCollectionName)
}
$row | Out-GridView

Saturday, 15 February 2014

Applying/Change the CustomMasterUrl and MasterUrl in master page setting in SharePoint using PowerShell

Provide the URL in $webAppUrl and Below is the code details:-

param($webAppUrl)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint.Administration")
 
$site=New-Object Microsoft.SharePoint.SPSite($webAppUrl)
$web = $site.openweb();
$web.AllowUnsafeUpdates=$true;
$MasterPageURL="/_catalogs/masterpage/XYZ_publishing.master"
$web.CustomMasterUrl=$MasterPageURL
$web.MasterUrl=$MasterPageURL
$web.Update()
$web.AllowUnsafeUpdates=$false;
$outputText = "XYZ publishing master page is applying in "+ $web.Name +" site."
write-output $outputText
                                
$web.Dispose()
$site.Dispose()

Friday, 14 February 2014

Upload Master Page in SharePoint Site using PowerShell

At first you create one folder like “Master Page Unload File” under the folder creates one more folder like “Doc” with two other files UploadMasterPages.bat and UploadMasterPages.ps1.
Master Page Unload File.
-  Doc
                - MasterPage.aspx (Store your master page under Doc folder)
-  UploadMasterPages.bat
-  UploadMasterPages.ps1

Please see the below code part:-   For UploadMasterPages.ps1


param($webAppUrl)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint.Administration")
 
$checkInComment="Check In"
$publishComment="published"
$approveComment="Approved"
$logfile = "UploadMasterPage_$(get-date -f yyyyMMdd_hhmmss).log"
$spsite = new-object Microsoft.Sharepoint.SPSite($webAppUrl);
$web = $spsite.RootWeb;
 
    $masterPageList = ($web).GetFolder("Master Page Gallery")
    # Get file system path
$filesfolde = Split-Path $script:MyInvocation.MyCommand.Path
 
$masterPageLocalDir = $filesfolde + "\Doc"
    #For upload all files in document library from file system
     
foreach ($file in Get-ChildItem $masterPageLocalDir)
      {
      $web.AllowUnsafeUpdates=$true;
     
try
{
      if ([Microsoft.SharePoint.Publishing.PublishingSite]::IsPublishingSite($spsite))
      {
     
      $stream = [IO.File]::OpenRead($file.fullname)
          $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
            $masterPageFile=$web.GetFile($destUrl)
      write-host($masterPageFile)
      write-host($destUrl)
      write-host($stream)
           if($masterPageFile.CheckOutStatus -ne "None")
            {
                       
                        $web.AllowUnsafeUpdates  = $true;
                        $masterPageList.files.Add($destUrl,$stream,$true)
                       
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);                              
                        $masterPageFile.Publish($publishComment);                       
                        $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
            }
          else
            {
                        $masterPageFile.CheckOut();
                        try{
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        }
                        catch
                        {
                        write-Output $_
                        }
                        $stream.close()                                       
                         $masterPageFile.CheckIn($checkInComment);                                     
                         $masterPageFile.Publish($publishComment);                                     
                         $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +  " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
            }
      }
     
      else
      {
     
            $stream = [IO.File]::OpenRead($file.fullname)
            $destUrl = $web.Url + "/_catalogs/masterpage/" +$file.Name
            $masterPageFile=$web.GetFile($destUrl)
             if($masterPageFile.CheckOutStatus -ne "None")
              {
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);                              
                        $masterPageFile.Publish($publishComment);                       
                        $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +  "Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
             else
               {
                        $masterPageFile.CheckOut();
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                       
                         $masterPageFile.CheckIn($checkInComment);                                     
                         $masterPageFile.Publish($publishComment);                                     
                         $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ "Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
              }
      }
     
     
}
catch
{
try
         {
     
           
            $stream = [IO.File]::OpenRead($file.fullname)
            $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
            $masterPageFile=$web.GetFile($destUrl)
             if($masterPageFile.CheckOutStatus -ne "None")
               {
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);
                       $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
              else
                {
 
                        $masterPageFile.CheckOut();
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);
                       $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +" Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
         }
      catch
         {
            write-Output $_ | out-File $logfile -Append
         } 
}
}
$web.dispose();
$spsite.dispose();

----------------------------------------------------------------------------------------------------
 Please see the below code part:-   For UploadMasterPages.bat

cls
 set startDate=%date%
set startTime=%time%
 set sdy=%startDate:~10%
set /a sdm=1%startDate:~4,2% - 100
set /a sdd=1%startDate:~7,2% - 100
set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100
set timestamp=%sdm%-%sdd%-%sdy%-%sth%-%stm%-%sts%
 time /t
 powershell.exe Set-ExecutionPolicy RemoteSigned
powershell.exe -noexit .\UploadMasterPages.ps1 "http://server-name.com/site/"
 time /t