About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.
Showing posts with label powershell script. Show all posts
Showing posts with label powershell script. Show all posts

Monday, 25 August 2014

Powershell Script - Create custom user profile properties in SharePoint 2013

The powershell script will create custom user profile properties by reading data from xml configuration file. The script accepts following input parameters

1. SiteUrl - Site colletion url
2. ManagedMetaDataServiceName - MMS service app name

Points to be noted

1. The MMS service is required, as one of the custom property gets data from predefined term set.
2. We need xml file which has required configuration.

Steps involved

1. Save following as xml file format, you can add as many as configurations you want and save as costumUserProfileProperties.xml and should be in the root directory of the script where you are running...

<?xml version="1.0" encoding="utf-8" ?>
<UserProfileProperties>
 
<Property Name="SkillSets" DisplayName="SkillSets" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

<Property Name="Interests" DisplayName="Interests" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

</UserProfileProperties>

   

2. Save following script as psCreateCustomUserProfileProperty.ps1
#-----------------------------------------------------------------------------
# Name:             psCreateCustomUserProfileProperty.ps1 
# Description:      This script will create termset names as 'Skills'
#                    and creates following user profile properties
#                   'Skills' & 'Interests'
#                    
# Usage:            Run the script by passing the paramter $SiteUrl,
#                   ManagedMetaDataServiceName
# Created By:       Vamsi Mohan Mitta
# Date:             01/07/2014
#-----------------------------------------------------------------------------

Param([Parameter(Mandatory=$true)]
      [String]
      $SiteUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $ManagedMetaDataServiceName     
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}
#Do not modify anything in the script from here onwards
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory

$logfile=$currentPhysicalPath + "\log.log"

Start-Transcript $logfile

#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl    # Central Admin URL  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]    # Meata data service name
write-host “Connection made with term store -” $termStore.Name -ForegroundColor Green

$termGroupName = "ECTermGroup"
#Create a group
      if ($termStore.Groups[$termGroupName] -eq $null)
      {
        $termGroup = $termStore.CreateGroup($termGroupName)
        $termStore.CommitAll()
        write-host “Successfully created term group -” $termGroupName -ForegroundColor Green
      }
      else
      { write-host “Term Group already -” $termGroupName " exists" -ForegroundColor Blue }

#Connect to existing term group
$termGroup = $termstore.groups[$termGroupName];

#TERM SETS
#Create a term set

    if($termGroup.TermSets["Skills"] -eq $null)
    {
    $createTermSet = $termGroup.CreateTermSet("Skills")
    $termStore.CommitAll()
    write-host “Successfully created term set” -ForegroundColor Green
    }
    else
      { write-host “Term Set already exists" -ForegroundColor Blue }


#Connect to existing term set
$termset = $termGroup.Termsets["Skills"]

$term = $termSet.CreateTerm("Sea wall",1033)
$term.SetDescription(“Sea wall”, 1033)
$term.CreateLabel("Seawall”, 1033, $false)

$term = $termSet.CreateTerm("Tunnels and bridges",1033)
$term.SetDescription(“Tunnels and bridges”, 1033)
$term.CreateLabel("Tunnelsandbridges”, 1033, $false)


$term = $termSet.CreateTerm("Water pipelines",1033)
$term.SetDescription(“Water pipelines”, 1033)
$term.CreateLabel("Waterpipelines”, 1033, $false)

$term = $termSet.CreateTerm("Desalination plants- Land reclamation",1033)
$term.SetDescription(“Desalination plants- Land reclamation”, 1033)
$term.CreateLabel("Desalinationplants”, 1033, $false)

$TermSet.IsOpenForTermCreation = $true;

# Contribute permission on term group
$user = "c:0(.s|true"
$termGroup.AddContributor($user)


$termStore.CommitAll()

#----------------This service application is the default storage location for column specific term sets---------------------------------------------------------------


# This service application is the default storage location for column specific term sets.  on proxy peroperty select this
# Get Metadata service application proxy
$metadataserviceapplicationname = $ManagedMetaDataServiceName
Set-SPMetadataServiceApplicationProxy -Identity $metadataserviceapplicationname -DefaultSiteCollectionTaxonomy:$true

#$metadataserviceapplicationproxy = get-spmetadataserviceapplicationproxy $metadataserviceapplicationname
#$metadataserviceapplicationproxy.Properties["IsDefaultSiteCollectionTaxonomy"] = $true

# Create a custom property with above term set as input.

#----------------Get the xml file---------------------------------------------------------------

 #[xml]$xmlData=Get-Content $xmlFilePath

 $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
 $filenamne = $scriptPath + '\' + "costumUserProfileProperties.xml"
 [xml]$xmlData=Get-Content $filenamne

#----------------Create new custom User Profile properties---------------------------------------------
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorVariable err -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")

function CreateUserProfileProperties($SiteUrl,$ManagedMetaDataServiceName)
{    
     
#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]

#Connect to existing term group
$termGroup = $termstore.groups["ECTermGroup"];
$termSetSkill = $termGroup.TermSets["Skills"]


      #$site = Get-SPSite $xmlData.UserProfileProperties.SiteURL
      $site = Get-SPSite $SiteUrl
      $context = Get-SPServiceContext($site)
      $upcm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context);     
      $ppm = $upcm.ProfilePropertyManager
      $cpm = $ppm.GetCoreProperties()
      $ptpm = $ppm.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User)
      $psm = [Microsoft.Office.Server.UserProfiles.ProfileSubTypeManager]::Get($context)
      $ps = $psm.GetProfileSubtype([Microsoft.Office.Server.UserProfiles.ProfileSubtypeManager]::GetDefaultProfileName([Microsoft.Office.Server.UserProfiles.ProfileType]::User))
      $pspm = $ps.Properties
      $xmlData.UserProfileProperties.Property | ForEach-Object{
            $property = $pspm.GetPropertyByName($_.Name)         
            if($property -eq $null)
            {
                $Privacy=$_.Privacy
                $PrivacyPolicy=$_.PrivacyPolicy
                $coreProp = $cpm.Create($false)
                $coreProp.Name = $_.Name
                $coreProp.DisplayName = $_.DisplayName
                $coreProp.Type = $_.Type
                $coreProp.Length = $_.Length
                 #$coreProp.IsTaxonomic=[Microsoft.SharePoint.Taxonomy.TermSet]$_.IsTaxonomic

                 $coreProp.TermSet=$termSetSkill

                $cpm.Add($coreProp)
                $profileTypeProp = $ptpm.Create($coreProp);
                $profileTypeProp.IsVisibleOnEditor = $true;
                $profileTypeProp.IsVisibleOnViewer = $true;

                $ptpm.Add($profileTypeProp)

                $profileSubTypeProp = $pspm.Create($profileTypeProp);
                $profileSubTypeProp.DefaultPrivacy = [Microsoft.Office.Server.UserProfiles.Privacy]::$Privacy
                $profileSubTypeProp.PrivacyPolicy = [Microsoft.Office.Server.UserProfiles.PrivacyPolicy]::$PrivacyPolicy
                $profileSubTypeProp.IsUserEditable = $true;  
                $profileSubTypeProp.AllowPolicyOverride        
               
                $pspm.Add($profileSubTypeProp)
                  write-host -f yellow $_.Name property is created successfully                
            }
            else
            {
               write-host -f yellow $_.Name property already exists
            }
      }
}
#----------------Calling the function--------------------------------------------- 
 CreateUserProfileProperties -SiteUrl $SiteUrl -ManagedMetaDataServiceName $ManagedMetaDataServiceName

 Stop-Transcript
 Echo Finish


Step2: Create batch file to run the script. Save file in .bat format.

cd /d %~dp0
powershell -file  ./psCreateCustomUserProfileProperty.ps1 -SiteUrl "xxxxx" -ManagedMetaDataServiceName "MMS_Proxy"
pause

Happy powershell coding... please feel free to comment...

Powershell Script - Modify Sharepoint web.config file entries

The following script will add/update SharePoint web.config file entries. The script accepts following input parameters. 

1. WebAppUrl - SharePoint web application url
2.WebConfigPath - Path for the SharePoint web application virtual directory

 Points to be noted
1. The following script backup existing web.config and add entries under configuration/appSettings & configuration/connectionStrings
 2. Provide input data in the form of .csv file with the separator as "$" with following header
 Configuration$Key$Value    
 Configuration is nothing but - the node where you want to add entries
3. The csv file should be in the same directory


Steps involved

1. Save following script as psUpdateSPWebApp.config.ps1


Param([Parameter(Mandatory=$true)]
      [String]
      $WebAppUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $WebConfigPath
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}

$objShell = New-Object -Com Shell.Application
$folder = $objShell.BrowseForFolder(0,"Please select the folder containing your CSV file:",0)
$pathfld = $folder.Self.Path
$fullpath = Join-Path $pathfld "xxxxx.csv"

# Show Farm BuildVersion to ensure the SharePoint .net library is loaded
$localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$localFarm.BuildVersion

# store some settings and objects in variables
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppUrl)
$farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" } )[0]


$currentDate = Get-Date -format MM-dd-yyyy-hh_mm_s # month-day-year - hours_mins_seconds
$backup = $WebConfigPath + "_$currentDate" + ".bak"

# Get the content of the config file and cast it to XML and save a backup copy labeled .bak followed by the date
$xml = [xml](get-content $WebConfigPath)
#save a backup copy
$xml.Save($backup)

$connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")

        if ($connectionStringsNode -eq $null)
        {        
        Write-Host "connectionStrings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $connectionStringsNode = $xml.CreateNode('element',"connectionStrings","")
        $configurationNode = $xml.configuration.AppendChild($connectionStringsNode)
        $connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created connectionStrings node" -ForegroundColor Green           
        }

$appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")

        if ($appSettingsNode -eq $null)
        {        
        Write-Host "appSettings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $appSettingsNode = $xml.CreateNode('element',"appSettings","")
        $configurationNode1 = $xml.configuration.AppendChild($appSettingsNode)
        $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created appSettings node:" -ForegroundColor Green
        }

Import-Csv -Delimiter "$" -Path $fullpath | % {

if($_.Configuration -eq "appSettings")
{
    $appSettings = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $appSettings.Path = “/configuration/appSettings”;

    $appSettings.Name = [system.string]::format(“add[@key=""{0}""]“, $_.Key);
    $appSettings.Value = [system.string]::format(“<add key=”"{0}”" value=”"{1}”" />”, $_.Key, $_.Value);

   
    $appSettings.Sequence = 0
    $appSettings.Owner = “SharePoint”
    $appSettings.Type = 0

    $webapp = Get-SPWebApplication $WebAppUrl
    $webapp.WebConfigModifications.Add($appSettings)
    $webapp.Update()
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created appSettings key:" $_.Key -ForegroundColor Green
}

elseif($_.Configuration -eq "connectionStrings")
{
    $value = $_.Value
    $connectionString = New-Object "Microsoft.SharePoint.Administration.SPWebConfigModification"
    $connectionString.Path = "configuration/connectionStrings"
    $connectionString.Name = "ECConnectionString"
    $connectionString.Sequence = 0 
    $connectionString.Type = 0 
    $connectionString.Owner = "ECConnectionStringOwner"
    $connectionString.Value = $value
    $webapp.WebConfigModifications.Add($connectionString)  #Update the Web Application and apply all existing web.config modifications 
    $webapp.Update() 
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created connectionStrings key:" $_.Key -ForegroundColor Green
}

}# end of second import


Step2: Create batch file to run the script. Save file in .bat format.
cd /d %~dp0
powershell -file ./psUpdateSPWebApp.config.ps1 -WebAppUrl "xxxxx" -WebConfigPath "C:\inetpub\wwwroot\wss\VirtualDirectories\443\web.config"
pause
 

Happy powershell coding... please feel free to comment...

Powershell Script - Upload App to AppCatalog store in SharePoint 2013

The following powershell script will upload .App file to App catalog and accept following input parameters

1. WebUrl - App Catalog site url
2.AppCatalogName - 'Apps for Sharepoint'
3.AppName - Your .app name

Note: The .app should be in the same directory where you are running the script.

Steps involved
1. Save following script as psUploadAppToCatalog.ps1


Param(           
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
[string]$WebUrl,           
[Parameter(Mandatory=$true)]           
[string]$AppCatalogName,           
[Parameter(Mandatory=$true)]           
[string]$AppName          


if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell";
}
    
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory
$logfile=$currentPhysicalPath + "\log.log"
Start-Transcript $logfile        

try
{
    Start-SPAssignment -Global             
    $spWeb = Get-SPWeb -Identity $WebUrl            
    $spWeb.AllowUnsafeUpdates = $true;           
    $List = $spWeb.Lists[$AppCatalogName]           
    $folder = $List.RootFolder
    $FilePath = $currentPhysicalPath + "\" + $AppName    
    #$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
           
    $File= Get-ChildItem $FilePath           
    [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile("/" + $folder.Url + "/" + $File.Name)           
    $flagConfirm = 'y'           

    #if($spFile.Exists -eq $true)           
    #{           
     #   $flagConfirm = Read-Host "File $AppName already exists in library $DocLibName, do you want to upload a new version(y/n)?"            
    #}           

    #if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')  
    if ($flagConfirm -eq 'y')       
    {           
        $fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()           
        #Add file           
        write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."           
        [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, [System.IO.Stream]$fileStream, $true)           
        write-host -f Green "...Success!"           
        #Close file stream           
        $fileStream.Close()
        write-host -f Green "Successssfully uploaded the app -" $AppName " to app catalog" -ForegroundColor Green     
    }              
$spWeb.AllowUnsafeUpdates = $false;
}

catch
{
        $Host.UI.RawUI.WindowTitle = " -- Error --"
        Write-Host -ForegroundColor Red $_.ToString()
        Write-Host -ForegroundColor Red $_.Exception.ToString()
}
Stop-Transcript         

Stop-SPAssignment -Global
            
Step2: Create batch file to run the script. Save file in .bat format.

cd /d %~dp0
powershell -file ./psUploadAppToCatalog.ps1 -WebUrl "https://catalog.ec.com" -AppCatalogName "Apps for SharePoint" -AppName "xxxxx.app"
pause

Happy powershell coding... please feel free to comment...

Powershell Script - Import BCS model along with permissions in SharePoint 2013

The following script will import BCS entity to SharePoint environment. The script need following as input parameters

1. Site Url
2.Admin user account
3.All users group (NT AUTHORITY\authenticated users)
4.Catalog Name (The BCS entity name which you are going to create/update)

Steps involved


Note: Make sure that, your .bdcm file should be in the current directory (where you are running your script)

1. Save following script as psDeployBCSModel.ps1

Param(           
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
[string]$SiteUrl,           
[Parameter(Mandatory=$true)]           
[string]$AdminUser,           
[Parameter(Mandatory=$true)]           
[string]$AllUsers,
[Parameter(Mandatory=$true)]           
[string]$CatalogName        
)

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell";
}
    
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

function SetBcsProfileHostUrl($bdc, $siteUrl)
{
    #$catalog = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Catalog" -ServiceContext $siteUrl
    $property = $bdc.Properties | Where { $_.Name -eq "Profile_HostURL" }
    if ($property) {
        $bdc.Properties.Remove("Profile_HostURL")
    }
    $bdc.Properties.Add("Profile_HostURL", $siteUrl)
    write-host write-host “Successfully added BCS profile page to the model-” -ForegroundColor Green
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory
$logfile=$currentPhysicalPath + "\log.log"
Start-Transcript $logfile

try
{
$bdc = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType Catalog -ServiceContext $SiteUrl
#$pathtobdcmfiles = Get-Location
$importFiles = Get-Childitem -path $currentPhysicalPath | Where {$_.extension -eq ".bdcm" -and $_.basename -ne "catalog"}

#$ecConvCatalog = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Catalog" -Name $CatalogName -ServiceContext $SiteUrl

#if($ecConvCatalog)
#{

#Remove-SPBusinessDataCatalogMetadataObject –Identity $ecConvCatalog
#write-host write-host “Successfully removed existing BCS model-” -ForegroundColor Green
#}

foreach ($file in $importFiles) {
     if($file -ne $null)
     {

         Import-SPBusinessDataCatalogModel -Path $file.FullName -Identity $bdc -force -ModelsIncluded -PropertiesIncluded -PermissionsIncluded -Verbose
         write-host write-host “Successfully imported BCS model-” $file.Name -ForegroundColor Green
    
         $claimAdmin = New-SPClaimsPrincipal -Identity $AdminUser -IdentityType WindowsSamAccountName
         $claimUsers = New-SPClaimsPrincipal -Identity $AllUsers -IdentityType WindowsSamAccountName

         $claimAdmin = New-SPClaimsPrincipal -Identity $AdminUser -IdentityType WindowsSamAccountName
         $claimUsers = New-SPClaimsPrincipal -Identity $AllUsers -IdentityType WindowsSamAccountName

         Grant-SPBusinessDataCatalogMetadataObject -Identity $bdc -Principal $claimAdmin -Right "Execute,SetPermissions,Edit,SelectableInClients"
         Grant-SPBusinessDataCatalogMetadataObject -Identity $bdc -Principal $claimUsers -Right "Execute"
         write-host write-host “Successfully granted access rights to BCS model-” $file.Name -ForegroundColor Green

         Copy-SPBusinessDataCatalogAclToChildren -MetadataObject $bdc
         write-host write-host “Successfully deployed BCS entity-” $file.Name -ForegroundColor Green
    }
}# end of for
   
SetBcsProfileHostUrl -bdc $bdc -siteUrl $SiteUrl
}
catch
{
    $Host.UI.RawUI.WindowTitle = " -- Error --"
    Write-Host -ForegroundColor Red $_.ToString()
    Write-Host -ForegroundColor Red $_.Exception.ToString()
}

Stop-Transcript


Step2: Create batch file to run the script. Save file in .bat format.

/cd /d %~dp0
powershell -file ./psDeployBCSModel.ps1 -SiteUrl "https://devpub.ec.com" -AdminUser "EC\SPBCS" -AllUsers "NT AUTHORITY\authenticated users" -CatalogName "ECConversation"
pause


Happy powershell coding... please feel free to comment...

Wednesday, 19 December 2012

PowerShell script to deploy Sandbox solution

Applies to SPFoundation 2010, SP 2010, SPFoundation 2013,SP 2013

In general we will write a script to deploy farm solutions. But we will upload sandbox solutions into site collection solution gallery. What if, we want to automate the process to deploy sandbox solution without uploading.... here is the script

Points to be noted:
1. The .wsp should be in the current directory of the script (.ps1)
2. Replace $solutionName with your solution name.
3. Replace $SiteURL with your site collection url.

Add-PsSnapin Microsoft.SharePoint.PowerShell
Write-Host 'Poweshell Script will initialize parameters'
$CurrentDir=$args[0]
$solutionName="xxxx.wsp"
$SolutionPath=$CurrentDir + "\"+$solutionName
$logfile=$CurrentDir + "\log.log"
$SiteURL = "xxxxxxx"

Start-Transcript $logfile
$errorActionPreference = 'Inquire'

$solution = Get-SPUserSolution -site $siteURL | Where { ($solutionName -eq $_.Name) }  -ErrorAction SilentlyContinue 
try
{
if ($solution -ne $null)
{
if($solution.Status -eq "Activated")
{
Write-Host 'Poweshell Script will now retract solution:' $solutionName

Uninstall-SPUserSolution -Identity $solutionName -Site $SiteURL -Confirm:$false
Write-Host 'Successfully retracted solution:' $solutionName
}
Write-Host 'Removing Solution:' $solutionName
Remove-SPUserSolution -Identity $solutionName -Site $siteURL -Confirm:$false
Write-Host 'Successfully removed Solution:' $solutionName
}

Write-Host 'Poweshell Script will now add solution:' $solutionName
Add-SPUserSolution –LiteralPath $SolutionPath -Site $SiteURL
Write-Host 'Poweshell Script will now deploy solution:' $solutionName
Install-SPUserSolution -Identity $solutionName -Site $SiteURL
Write-Host 'Poweshell Script has finished deployment of solution:' $solutionName
}

catch [system.Exception]
{
Write-Error 'An Unknown error occured while trying to deploy/redeploying the solution:' $_.Exception.Message
}


Stop-Transcript
Remove-PsSnapin Microsoft.SharePoint.PowerShell

Happy powershell programming......