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

Friday, December 26, 2014

SharePoint 2013 App Deployment PowerShell

In SharePoint 2013 App Development and Deployment we come across situations to automate the Upload and Install of SharePoint 2013 App to Corporate Catalog. Please find below the PowerShell to automate that process.

#-----Function to Load SharePoint PowerShell Environment----#
function LoadSharePointPowerShellEnvironment
{
    write-host "Setting up PowerShell environment for SharePoint..." -foregroundcolor Yellow
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
    write-host "SharePoint PowerShell Snapin loaded." -foregroundcolor Green
}
#-----Function to create output log file--#
function CreateLogFile {
param($logFileName)
 New-Item $logFileName -type File
 Set-Content $logFileName "Starting App Upload and Deployment......"
}
function Main($inputAppCatalogSiteCollectionUrl, $inputFolderLocation, $inputSiteCollectionUrl)
{
    try
    {
        $logFileName = [System.String]::Format("{0}{1}_{2}_{3}{4}", $inputFolderLocation + "\","Output_", $dateSuffix, $timeSuffix,".csv")
       
        $sourceApp = ([microsoft.sharepoint.administration.spappsource]::CorporateCatalog)
       
        $inputAPPName = "Test.app"       
        $inputAPPPath = [System.String]::Format("{0}{1}", $inputFolderLocation + "\", $inputAPPName)
        CreateLogFile $logFileName
       
        #Uploading app in app Catalog       
        UploadFile $inputAppCatalogSiteCollectionUrl "Apps for SharePoint" $inputAPPPath          
            
        Write-Host "APP added in App Catalog -" $inputSiteCollectionUrl;
        Write-Host "Import to Destination Site started"  $inputSiteCollectionUrl;
       
        #Importing app
        $spapp =Import-SPAppPackage -Path  $inputAPPPath -Site $inputSiteCollectionUrl -Source $sourceApp    
        Write-Host "Import to Destination Site Completed"  $inputSiteCollectionUrl;            
        Write-Host "Installation to Destination Site Started"  $inputSiteCollectionUrl;
        #Installing app
        $instance = Install-SPApp -Web $inputSiteCollectionUrl -Identity $spapp
        Write-Host "Installation to Destination Site Completed"  $inputSiteCollectionUrl;
}
catch
{
    Write-Host "Error Occured: $_.Exception.Message"
    Add-Content $logFileName "Error in Method Main."
    Add-Content $logFileName "Error Details: $_.Exception.Message"
}
}

function UploadFile($WebURL, $DocLibName, $FilePath)
{
    try
    {
        $Web = Get-SPWeb $WebURL
        if($Web -ne $null)
        {               
            $List = $Web.GetFolder($DocLibName)
           
            $Files = $List.Files
           
            $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
           
            $folder = $List.RootFolder
            $SPFilePath = ($folder.URL + "/" + $FileName)
           
            $spFile = $web.GetFile($SPFilePath)
           
            if ($spFile -ne $null)
            {
                Write-Host "Already Exist in App Catalog-" $inputSiteCollectionUrl;
                Write-Host "OverWriting Existing file in App Catalog-" $inputSiteCollectionUrl;
            }
           
            $File= Get-ChildItem $FilePath
            $Files.Add("AppCatalog/" + $FileName, $File.OpenRead(), $true)
        }
        else
        {
            Write-Host "Web not found for URL : -" $inputSiteCollectionUrl;
            write-host "Method: Main, SPWeb Object is null." -foregroundcolor "Yellow"
            Add-Content $logFileName "Method: Main, SPWeb Object is null."
        }
    }
    catch
    {
        Write-Host "Error Occured: $_.Exception.Message"
        Add-Content $logFileName "Error in Method Main."
        Add-Content $logFileName "Error Details: $_.Exception.Message"
    }
    finally
    {
        if($spWeb -ne $null)
        {
            $spWeb.Dispose()
        }
    }
}
# Calling LoadSharePointPowerShellEnvironment Method
LoadSharePointPowerShellEnvironment
Main "http://AppCatalog.qa" "C:\Solutions" "http://abc-pc1873-1/sites/abc/"

Thanks, Prabhat

Sunday, October 21, 2012

SharePoint 2010: Attach Disposition Workflow To Content Type using PowerShell

Hi Friends,

Many times we are needed to attach a "Disposition Workflow" with a Content Type in SharePoint 2010. This is pretty easy to accoplish. Please find the PowerShell to do this.

# Method Calling
AddWorkflowToContentType $site $ContentTypeName "Disposition Approval" "WFA" $TaskListName

#Method Definition
function AddWorkflowToContentType($site, $ctName, $WfName, $WfAssociationName, $TaxTaskList)
   {
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint')
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Office.Policy')
  
    [Guid]$wfTemplateId = New-Object Guid
    $web = $site.RootWeb
       $ct = $web.ContentTypes[$ctName]
       $culture = New-Object System.Globalization.CultureInfo("en-US")
       $template = $site.RootWeb.WorkflowTemplates.GetTemplateByName($WfName, $culture)
   
       if($template -ne $null)
       {                       
      $tasklist = $TaxTaskList
                     $historylist = "Workflow History"
                    
                        # Checking For WorkFlow History List; If not exists then create it
                        if(!$web.Lists[$historylist])
                        {
                            $web.Lists.Add($historylist, "A system library used to store workflow history information that is created in this site.  It is created by the Publishing feature.",
                            "WorkflowHistory", "00BFEA71-4EA5-48D4-A4AD-305CF7030140", 140, "100")
                           
       if (!$web.Features["00BFEA71-4EA5-48D4-A4AD-305CF7030140"]) {
                                Enable-SPFeature -Identity WorkflowHistoryList -Url $web.Url
                            }
      
                            $wfHistory = $web.Lists[$historylist]
                            $wfHistory.Hidden = $true
                            $wfHistory.Update()
                        }

                        # Checking For WorkFlow Task List; If not exists then create it
                        if(!$web.Lists[$tasklist])
                        {
                            $web.Lists.Add($tasklist, "This system library was created by the Publishing feature to store workflow tasks that are created in this site.", "WorkflowTasks", "00BFEA71-A83E-497E-9BA0-7A5C597D0107", 107, "100")
                        }
     
                        # Creating Workflow Association with Content Type
                        $association = [Microsoft.SharePoint.Workflow.SPWorkflowAssociation]::CreateSiteContentTypeAssociation($template, $WfAssociationName, $web.Lists[$tasklist], $web.Lists[$historylist])
                       
      $association.AllowManual = $false
                        #$association.AutoStartCreate = $true
                        $ct.AddWorkflowAssociation($association)
                        $ct.UpdateWorkflowAssociationsOnChildren($true, $true, $true, $false)
                        $association.Enabled=$true
                        $ct.Update()
                        $web.Update()
                        #$ct.WorkflowAssociations[0]           
       }
       else
       {
        Write-Error "Workflow Template not found"
                    Add-Content $logFileName "Workflow Template not found."
       }
   }

Happy Coding!!!

Prabhat

Monday, September 3, 2012

PowerShell To create Retention Policies for Content Types

Hi Friends,

PowerShell is really a very powerful tool. Its not just a command prompt, we can also do coding into this.
Here I am using Powershell to create Policies on Content Types. I am creating Retention Policies and Auding Policy on Content Types. I am using One file "D:\Test\ContentTypes.txt" which contains data(content types) description according which we are applying Policies on those.

Data in the "D:\Test\ContentTypes.txt" will be in following format:

Name,Property,Period,PeriodType
One CTypeName,Created,15,Years
Two CTypeName,Created,25,Years
Three CTypeName,Created,Permanent,Years

function  abc()
{
$url = "http://server:1717/sites/TestTopLevelSite/"

$site = get-spsite $url
$web = $site.openweb()

Enable-SPFeature –identity "LocationBasedPolicy" -URL $url -ErrorAction SilentlyContinue

$CTList = Import-Csv D:\Test\ContentTypes.txt

echo "Processing Content Types"

ForEach ($item in $CTList){

$Name = $($item.Name)
$Property = $($item.Property)
$Period = $($item.Period)
$PeriodType = $($item.PeriodType)

$contentType = $web.ContentTypes[$Name]

if (($Period -ne "IND") -or ($Period -notcontains "MAX")) {

if($contentType){

[Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::CreatePolicy($contentType, $null);

$newPolicy = [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($contentType);

$newPolicy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration",
 "<Schedules nextStageId='3'>"+
 "<Schedule type='Default'>"+
 "<stages>"+
 "<data stageId='1' stageDeleted='true'></data>"+
 "<data stageId='2'>"+
 "<formula id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn'>"+
 "<number>"+$Period+"</number>"+"<property>"+$Property+"</property>"+
 "<period>"+$PeriodType+"</period>"+
 "</formula>"+
 "<action type='action' id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Action.MoveToRecycleBin' />"+
 "</data>"+
 "</stages>"+
 "</Schedule>"+
 "</Schedules>");

$newPolicy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.PolicyAudit",
 "<Audit>"+
 "<Update />"+
 "<View />"+
 "<CheckInOut />"+
 "<MoveCopy />"+
 "<DeleteRestore />"+
 "</Audit>");

$newPolicy.Update();

}
}
}

$web.Dispose()
$site.Dispose()

echo "Finished!!!"

}

Happy Reading!!!