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

Sunday, June 5, 2016

Getting the files modified by a specified user

If you have any requirement to find out the files which has been modified by a specific user in sharepoint online.

Then here is the powershell script which will serve the purpose.

param
(
    [Parameter(Mandatory=$true)]
    [string]$SPSite,

    [Parameter(Mandatory=$true)]
    [string]$LoginName
)

function GetWebFiles($ctx, $web, $userId)

    Write-Host
    write-host "SITE: $($web.Url)"

    # Create a new custom object to hold our result.
    $siteObject = new-object PSObject

    # Add our data to $contactObject as attributes using the add-member commandlet
    $siteObject | add-member -membertype NoteProperty -name "Site URL" -Value $($web.Url)

    # Save the current $contactObject by appending it to $resultsArray ( += means append a new element to ‘me’)
    $resultsarray += $siteObject
    
    $strQuery = "<View Scope='RecursiveAll'><Query><Where><And>
                <Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq>
                <Or><Eq><FieldRef ID='Author' LookupId='True' /><Value Type='Lookup'>$($user.Id)</Value></Eq>
                <Eq><FieldRef ID='Editor' LookupId='True' /><Value Type='Lookup'>$($user.Id)</Value></Eq></Or>
                </And></Where></Query></View>"                  
     
    $lists = $web.Lists
        
    $ctx.Load($lists)
    $ctx.ExecuteQuery()

    foreach ($l in $lists)
    {       
        if ($l.BaseType.ToString() -eq "DocumentLibrary")
        {
            $camlQuery = new-object Microsoft.SharePoint.Client.CamlQuery
            $camlQuery.ViewXml = $strQuery

            $items = $l.GetItems($camlQuery)

            $ctx.Load($items)
            $ctx.ExecuteQuery()
       
            if ($items.Count -gt 0)
            {
                foreach ($item in $items)
                {
                    Write-Host "$($SPSite)$($item["FileRef"])" #"$($web.Url)$($item["FileRef"])"

                    # Create a new custom object to hold our result.
                    $siteObject = new-object PSObject

                    # Add our data to $contactObject as attributes using the add-member commandlet
                    $siteObject | add-member -membertype NoteProperty -name "Site URL" -Value "$($web.Url)$($item["FileRef"])"

                    # Save the current $contactObject by appending it to $resultsArray ( += means append a new element to ‘me’)
                    $resultsarray += $siteObject
                }
            }
        }       
    }
   
    $subWebs = $web.Webs

    $ctx.Load($subWebs)
    $ctx.ExecuteQuery()

    foreach ($subWeb in $subWebs)
    {
        GetWebFiles $ctx $subWeb $userId
    }
}

$username = Read-Host -Prompt "Enter Username"
$password = Read-Host -Prompt "Enter Password" -AsSecureString

$scriptPath = Split-Path $MyInvocation.MyCommand.Path

Add-Type -Path "$($scriptPath)\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$($scriptPath)\Microsoft.SharePoint.Client.Runtime.dll"

# Declare an array to collect our result objects
$resultsarray =@()

try
{
    $teamSites = import-csv “$($scriptPath)\O365DTeamSites.csv”

    ForEach ($item in $teamSites)
    {
        $siteUrl = $item.(“Site URL”)

        #Write-Output “Site URL: $siteUrl”

        try
        {
            $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
   
            $creds = New-Object System.Net.NetworkCredential($username, $password)
            $ctx.Credentials = $creds;
                      
            $user = $ctx.Web.SiteUsers.GetByLoginName($LoginName)
                            
            $rootWeb = $ctx.Site.RootWeb  

            $ctx.Load($rootWeb)
            $ctx.Load($user)
            $ctx.ExecuteQuery()

            GetWebFiles $ctx $rootWeb $user.Id       
        }
        catch [Exception]
        {
            if($($_.Exception.Message) -ne "User cannot be found.")
            {
                write-host "Error checking site: $($siteUrl) -> $($_.Exception.Message)"
            }
            continue;
        }
    }

    $resultsarray| Export-csv $($scriptPath)\UserSites.csv -notypeinformation
}
catch [Exception]
{
    write-host "Error -> $($_.Exception.Message)"
    continue;
}


Happy Coding!!!

Thursday, October 16, 2014

Create and Configure Search Service Application in SharePoint 2013 using PowerShell



The core search architecture of SharePoint 2013 has a more complex and flexible topology that can be changed more efficiently by using Windows PowerShell. Each Search service application has its own search topology. If you create more than one Search service application in a farm, it’s recommended to allocate dedicated servers for the search topology of each Search service application.

In this blog, we will see how to configure topology for one search service application with multiple search components across 2 servers for redundancy and performance.

#==============================================================
#Search Service Application Configuration Settings
#==============================================================

$SearchApplicationPoolName = " SearchApplicationPool"$SearchApplicationPoolAccountName = "Contoso\Administrator"$SearchServiceApplicationName = "Search Service Application"$SearchServiceApplicationProxyName = "Search Service Application Proxy"$DatabaseServer = "2013-SP"$DatabaseName = "SP2013 Search"$IndexLocationServer1 = "D:\SearchIndexServer1"mkdir -Path $IndexLocationServer1 -Force$IndexLocationServer2 = "D:\SearchIndexServer2"mkdir -Path $IndexLocationServer2 -Force

#==============================================================
#Search Application Pool
#==============================================================

Write-Host -ForegroundColor DarkGray "Checking if Search Application Pool exists"$SPServiceApplicationPool = Get-SPServiceApplicationPool -Identity$SearchApplicationPoolName -ErrorAction SilentlyContinueif (!$SPServiceApplicationPool){ Write-Host -ForegroundColor Yellow "Creating Search Application Pool"$SPServiceApplicationPool = New-SPServiceApplicationPool -Name$SearchApplicationPoolName -Account $SearchApplicationPoolAccountName -Verbose}

#==============================================================
#Search Service Application
#==============================================================

Write-Host -ForegroundColor DarkGray "Checking if SSA exists"$SearchServiceApplication = Get-SPEnterpriseSearchServiceApplication-Identity $SearchServiceApplicationName -ErrorAction SilentlyContinueif (!$SearchServiceApplication){ Write-Host -ForegroundColor Yellow "Creating Search Service Application"$SearchServiceApplication = New-SPEnterpriseSearchServiceApplication -Name$SearchServiceApplicationName -ApplicationPool $SPServiceApplicationPool.Name-DatabaseServer $DatabaseServer -DatabaseName $DatabaseName}Write-Host -ForegroundColor DarkGray "Checking if SSA Proxy exists"$SearchServiceApplicationProxy = Get-SPEnterpriseSearchServiceApplicationProxy-Identity $SearchServiceApplicationProxyName -ErrorAction SilentlyContinueif (!$SearchServiceApplicationProxy){ Write-Host -ForegroundColor Yellow "Creating SSA Proxy"New-SPEnterpriseSearchServiceApplicationProxy -Name$SearchServiceApplicationProxyName -SearchApplication$SearchServiceApplicationName}

#==============================================================
#Start Search Service Instance on Server1
#==============================================================

$SearchServiceInstanceServer1 = Get-SPEnterpriseSearchServiceInstance -local Write-Host -ForegroundColor DarkGray "Checking if SSI is Online on Server1" if($SearchServiceInstanceServer1.Status -ne "Online") { Write-Host -ForegroundColor Yellow "Starting Search Service Instance" Start-SPEnterpriseSearchServiceInstance -Identity $SearchServiceInstanceServer1 While ($SearchServiceInstanceServer1.Status -ne "Online") { Start-Sleep -s 5 } Write-Host -ForegroundColor Yellow "SSI on Server1 is started" }

#==============================================================
#Start Search Service Instance on Server2
#==============================================================

$SearchServiceInstanceServer2 = Get-SPEnterpriseSearchServiceInstance -Identity
"2013-SP-AFCache" Write-Host -ForegroundColor DarkGray "Checking if SSI is Online on Server2" if($SearchServiceInstanceServer2.Status -ne "Online") { Write-Host -ForegroundColor Yellow "Starting Search Service Instance" Start-SPEnterpriseSearchServiceInstance -Identity $SearchServiceInstanceServer2 While ($SearchServiceInstanceServer2.Status -ne "Online") { Start-Sleep -s 5 } Write-Host -ForegroundColor Yellow "SSI on Server2 is started" }

#==============================================================
#Cannot make changes to topology in Active State.#Create new topology to add components
#============================================================== $InitialSearchTopology = $SearchServiceApplication |
Get-SPEnterpriseSearchTopology -Active
$NewSearchTopology = $SearchServiceApplication | New-SPEnterpriseSearchTopology

#==============================================================
#Search Service Application Components on Server1#Creating all components except Index (created later)
#==============================================================

New-SPEnterpriseSearchAnalyticsProcessingComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer1 New-SPEnterpriseSearchContentProcessingComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer1 New-SPEnterpriseSearchQueryProcessingComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer1 New-SPEnterpriseSearchCrawlComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1
New-SPEnterpriseSearchAdminComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1

#==============================================================
#Search Service Application Components on Server2.#Crawl, Query, and CPC
#==============================================================

New-SPEnterpriseSearchContentProcessingComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer2 New-SPEnterpriseSearchQueryProcessingComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer2 New-SPEnterpriseSearchCrawlComponent -SearchTopology
$NewSearchTopology -SearchServiceInstance $SearchServiceInstanceServer2


Server1
Primary
Server2
Primary
IndexPartition 0
IndexComponent 1

True
IndexComponent 2
False
IndexPartition 1
IndexComponent 3
False

IndexComponent 4

True
IndexPartition 2
IndexComponent 5

True
IndexComponent 6
False
IndexPartition 3
IndexComponent 7
False
IndexComponent 8

True



#==============================================================
#Index Components with replicas
#==============================================================

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1 -IndexPartition 0
-RootDirectory $IndexLocationServer1

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer2 -IndexPartition 0
-RootDirectory $IndexLocationServer2

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer2 -IndexPartition 1
-RootDirectory $IndexLocationServer2

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1 -IndexPartition 1
-RootDirectory $IndexLocationServer1

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1 -IndexPartition 2
-RootDirectory $IndexLocationServer1

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer2 -IndexPartition 2
-RootDirectory $IndexLocationServer2

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer2 -IndexPartition 3
-RootDirectory $IndexLocationServer2

New-SPEnterpriseSearchIndexComponent -SearchTopology $NewSearchTopology
-SearchServiceInstance $SearchServiceInstanceServer1 -IndexPartition 3
-RootDirectory $IndexLocationServer1

#==============================================================
#Setting Search Topology using Set-SPEnterpriseSearchTopology
#==============================================================
Set-SPEnterpriseSearchTopology -Identity $NewSearchTopology

#==============================================================
#Clean-Up Operation
#==============================================================
Write-Host -ForegroundColor DarkGray "Deleting old topology"
Remove-SPEnterpriseSearchTopology -Identity $InitialSearchTopology
-Confirm:$false
Write-Host -ForegroundColor Yellow "Old topology deleted"

#==============================================================
#Check Search Topology
#==============================================================
Get-SPEnterpriseSearchStatus -SearchApplication $SearchServiceApplication -Text
Write-Host -ForegroundColor Yellow "Search Service Application and Topology
is configured!!"
$Server02 = (Get-SPServer "2013-SPHost2").Name
$EnterpriseSearchserviceApplication = Get-SPEnterpriseSearchserviceApplication
$ActiveTopology = $EnterpriseSearchserviceApplication.ActiveTopology.Clone()
$IndexComponent =(New-Object Microsoft.Office.Server.Search.Administration.Topology.IndexComponent
$Server02,1);
$IndexComponent.RootDirectory = "D:\IndexComponent02"



# Server1 is the local server where the script is run.

For fault-tolerance we need to have at least two index components (replicas) for an index partition. Here I create 4 index partition with 8 index components. One index partition can serve up to 10 million items. As a good practice, the primary and secondary replicas should be balanced among the index servers. So we will have Server1 hosting 4 index component (out of which 2 will be primary replicas) and Server2 hosting other 4 index components (2 primary replicas).



* Please note that above cmdlets will not create the primary replicas in the server we want as expected as we are running all the cmdlets at same time without saving the topology. Ideally we should create an index partition in one server and then run Set-SPEnterpriseSearchTopology. This will ensure that the primary replica is created in the server we want. The next time you run the same cmdlet in another server for same index partition will create secondary replica. For more details - http://blogs.technet.com/b/speschka/archive/2012/12/02/adding-a-new-search-partition-and-replica-in-sharepoint-2013.aspx

When the above script is run one after the other to create multiple index partitions and replicas in different servers, you can see in the picture below there is no particular order for creation of replicas in the servers. The Primary and secondary replicas are not created in the servers that we wanted. If you are concerned about primary index component server location, then you should set the topology before you run the cmdlet to create secondary replica in another server.






Now that all search components are created in our new topology. Before setting our new topology we need to activate this topology. Remember that we also have an old topology which is in active state.



We will use Set-SPEnterpriseSearchTopology cmdlet which does some important tasks - Activates the NewTopology [$NewSearchTopology.Activate()], deactivates all other active topologies and sets the NewTopology(Active) as the current Enterprise Search Topology

#==============================================================
   #Setting Search Topology using Set-SPEnterpriseSearchTopology
 #==============================================================
 Set-SPEnterpriseSearchTopology -Identity $NewSearchTopology

After running Set-SPEnterpriseSearchTopology cmdlet, it will look like



As Set-SPEnterpriseSearchTopology has already done most of the job for us we will do one last thing - delete the old topology as its no longer required.

#==============================================================
                 #Clean-Up Operation
 #==============================================================
 Write-Host -ForegroundColor DarkGray "Deleting old topology"
 Remove-SPEnterpriseSearchTopology -Identity $InitialSearchTopology
 -Confirm:$false
 Write-Host -ForegroundColor Yellow "Old topology deleted"


When $SearchServiceApplication | Get-SPEnterpriseSearchTopology cmdlet is run, you will find just one topology (new topology that we created)



#==============================================================
                 #Check Search Topology
 #==============================================================
 Get-SPEnterpriseSearchStatus -SearchApplication $SearchServiceApplication -Text
 Write-Host -ForegroundColor Yellow "Search Service Application and Topology
 is configured!!"

In Central administration, Search service application you will find topology like this;



In your environment to know the numbers for each search components, use this scaling guidelines.



* The New-SPEnterpriseSearchIndexComponent requires folder for storing index files. In multiple server search configuration scenario, New-SPEnterpriseSearchIndexComponent checks the existence of RootDirectory in the wrong server. It checks the existence of the folder only in the machine where PowerShell script is executed; even in those cases when new index component is scheduled for other machine. You will get an error message, New-SPEnterpriseSearchIndexComponent : Cannot bind parameter 'RootDirectory'

There are 2 workarounds for this;

1. Create the folder manually in the machine that runs powershell script as its done in the aforementioned script.

2. Use directly the SP Object model instead of cmdlets.

$Server02 = (Get-SPServer "2013-SPHost2").Name
 $EnterpriseSearchserviceApplication  = Get-SPEnterpriseSearchserviceApplication
 $ActiveTopology = $EnterpriseSearchserviceApplication.ActiveTopology.Clone()
 $IndexComponent =(New-Object Microsoft.Office.Server.Search.Administration.Topology.IndexComponent
 $Server02,1);
 $IndexComponent.RootDirectory = "D:\IndexComponent02"
 $ActiveTopology.AddComponent($IndexComponent)

* A note on removing an index component - If you have more than one active index replica for an index partition, you can remove an index replica by performing the procedure Remove a search component in the article Manage search components in SharePoint Server 2013. You cannot remove the last index replica of an index partition using this procedure. If you have to remove all index replicas from the search topology, you must remove and re-create the Search service application and create a completely new search topology that has the reduced number of index partitions.





Sunday, September 28, 2014

Powershelll scripts for Feature activation

Enable-SPFeature -identity "<Feature ID>" -URL http://sharepointsite

Attach an existing content database to the farm using PowerShell script

The Mount-SPContentDatabase cmdlet attaches an existing content database to the farm. If the database being mounted requires an upgrade, this cmdlet will cause the database to be upgraded.

The default behavior of this cmdlet causes an upgrade of the schema of the database and initiates upgraded builds for all site collections within the specified content database if required. To prevent initiation of upgraded builds of site collections, use the NoB2BSiteUpgrade parameter. This cmdlet does not trigger version-to-version upgrade of any site collections.

Syntax:


Mount-SPContentDatabase [-Name] <String> [-WebApplication] <SPWebApplicationPipeBind> [-AssignmentCollection <SPAssignmentCollection>] [-AssignNewDatabaseId <SwitchParameter>] [-ChangeSyncKnowledge <SwitchParameter>] [-ClearChangeLog <SwitchParameter>] [-Confirm [<SwitchParameter>]] [-DatabaseCredentials <PSCredential>] [-DatabaseServer <String>] [-MaxSiteCount <Int32>] [-NoB2BSiteUpgrade <SwitchParameter>] [-SkipIntegrityChecks <SwitchParameter>] [-WarningSiteCount <Int32>] [-WhatIf [<SwitchParameter>]]


Example:

Mount-SPContentDatabase "MyDatabase" -DatabaseServer "MyServer" -WebApplication http://sitename


This example mounts an existing database to the sitename web application. If upgrades are required, it triggers database schema upgrade and then performs only build-to-build upgrade actions on existing site collections if required. This operation does not changed the CompatibilityLevel for existing site collections in this database.

Mount-SPContentDatabase "MyDatabase" -DatabaseServer "MyServer" -WebApplication http://sitename -NoB2BSiteUpgrade

This example mounts an existing database to the sitename web application but it prevents any site upgrades from occurring. If upgrades are required, it triggers database schema upgrades only and no build-to-build upgrade actions are performed on any site collections. This operation does not change the CompatibilityLevel for existing site collections in this database.

For More Info:

http://technet.microsoft.com/en-us/library/ff607581(v=office.15).aspx

Clean up SharePoint User Profile Store using PowerShell

Today i had a problem in my development environment for my SharePoint Projects regarding User Profile Store. My user profile was a messed up and was not available for editing in central administration. When i searched for my profile it still there but not shown for administration.  This was a really strange behavior because a couple of days it worked well. I added various new profile properties to my user profile service application. So the recreation of User Profile Service 
Application was not an option. Deletion of orphan or corrupted user profiles is not possible using Central Administration or even using avaliable PowerShell commands.

But there is a solution using PowerShell without compiled code. Using PowerShell everything what is avaliable in the server object model is avaliable. First of all two assemblies must be referenced.
These assemblies are:

These assemblies are:

Script:

/* Load required Assemblies for SharePoint Server and User Profile */
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Office.Server”)
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Office.Server.UserProfiles”)
/* Central Adminstration URL or any Web Application*/
$url = "http://myserver:Port"
/* Create a new Context Object */
$contextWeb = New-Object Microsoft.SharePoint.SPSite("http://servername");
/* Get the right Service Context */
$ServerContext = [Microsoft.Office.Server.ServerContext]::GetContext($contextWeb);
/* create a new connection to the UserProfileManager */
$UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServerContext);
/* Ger all User Profiles */
$Profiles = $UserProfileManager.GetEnumerator();
/* Loop through user profile */
foreach ($oUser in $Profiles ) {
/* Remove Profile */
$UserProfileManager.RemoveUserProfile($oUser.item("AccountName"));
}

This script can be extended to delete only specific users from user profile information. At the end I was able to solve my problem. My User Profile was deleted and recreated on first access and due profile import. Everything worked fine.

In the old days you had to write some custom command line tool to address those batch update and deletion task. With the introduction of PowerShell to SharePoint any possible administrative task could be accomplished by just use scripting.

Those assemblies could be referenced using System.Reflection and the rest of the script is quite simple SharePoint Development. So get a context object, open profile service application get all use and delete them.

Update Mysites/UserProfile user image url

I have recently had reason to update the PictureURL property value via PowerShell in SharePoint 2013 for all users in the system.
As a result, I wrote the following PowerShell script to update the property value using string replace.

You will ideally need to run this on the server with an account with the appropriate permissions to update all user profiles.

Script:

#Set up default variables
  
  #My Site URL
  $mySiteUrl = "http://mysite/"
  
  #The part of the picture URL you are trying to find
  $currentURLValue = "http://mypersonalsite"
  
  #The value that will replace the above
 $newURLValue = "http://mysite:80"
 #The internal name for PictureURL
 $upPictureURLAttribute = "PictureURL"
 #Get site objects and connect to User Profile Manager service
 $site = Get-SPSite $mySiteUrl
 $context = Get-SPServiceContext $site
 $profileManager = New-Object   Microsoft.Office.Server.UserProfiles.UserProfileManager($context) 
 $profiles = $profileManager.GetEnumerator()
 foreach ($userProfile in $profiles) {
  if ($userProfile[$upPictureURLAttribute] -ne '') {
    
    $newPictureURL = $userProfile[$upPictureURLAttribute].toString()
    $newPictureURL  = $newPictureURL.Replace($currentURLValue, $newURLValue)
    
    write-host "Before: " $userProfile[$upPictureURLAttribute].toString() " | After: " $newPictureURL 
    
    #Get user profile and change the value - uncomment the lines below to commit the changes
    #$userProfile[$upPictureURLAttribute].Value = $newPictureURL
    #$userProfile.Commit()
  }
 }

Get the Site Collection url's for a specific Data base using Powershell script

Get-SPSite -Limit All -ContentDatabase "DBTestSiteCol" | Select URL, Owner, SecondaryOwner | Export-CSV C:\SiteInfoDB.csv -NoTypeInformation

Saturday, September 27, 2014

Powershell scripts for the Infopath Form.

Please find the list of powershell scripts for the Infopath Form.

  1. Installs an InfoPath 2013 form template on a farm: [http://technet.microsoft.com/en-us/library/ff608053(v=office.15).aspx]


Install-SPInfoPathFormTemplate [-Path] <String> [-AssignmentCollection <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-EnableGradualUpgrade <SwitchParameter>] [-NoWait <SwitchParameter>] [-WhatIf [<SwitchParameter>]]

---------------EXAMPLE--------------
è Install-SPInfoPathFormTemplate -Path c:\Form.xsn

     
è "FormTemplateFirst.xsn", "FormTemplateSecond.xsn", "FormTemplateThird.xsn" | Install-SPInfoPathFormTemplate
This example installs multiple form templates on a farm

     2.   Saves InfoPath 2013 form templates on the SharePoint Central Administration Web site and .udcx files to a .cab file. [http://technet.microsoft.com/en-us/library/ff608075(v=office.15).aspx]

Export-SPInfoPathAdministrationFiles [-Path] <String> [-AssignmentCollection <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-Identity <SPFormsServicePipeBind>] [-WhatIf [<SwitchParameter>]]

---------------EXAMPLE--------------
è Export-SPInfoPathAdministrationFiles -path d:\file.cab

This example saves all InfoPath 2013 form templates (.xsn files) and universal data connections (.udcx files) located on the SharePoint Central Administration Web site in a compressed cabinet file named file.cab



For more information on InfoPath Services cmdlets in SharePoint Server 2013.

Update the web part property using powershell script

Sometimes you need to change the properties of a Web Part without browsing to the page itself and set it. There could be numerous reasons as to why you would want or need to do this. A while back I created a really simple redirect web part for one of my clients. It had two custom properties, EnableRedirect and Url. If EnableRedirect was true, it would redirect the user to the specified Url. Obviously, if you want to change either of these properties while the EnableRedirect is true, that's going to be a problem.
Fast forward and the redirect web parts need to be changed and/or disabled. Obviously we can't navigate to the page and just change it, because the page will redirect you. But it can be done relatively easy using PowerShell.
Start out with opening the site and getting the file we want to work on. Also note that the site I'm working on is a publishing site, which is why we need to check out, check in and publish the page we want to change the web part on.

$site = new-object Microsoft.SharePoint.SPSite("http://sharepointsite")$web = $site.OpenWeb("RandomSite/AnotherSite/")$page = $web.GetFile("Pages/default.aspx")$page.CheckOut()$wpm = $web.GetLimitedWebPartManager("Pages/default.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

From here we can look up and see which web parts are currently active on the page.
$wpm.WebParts | ft

There are two web parts on this page currently, and we want to change the second one. Let's finish of the script by doing this:
$wp = $wpm.WebParts[1]$wp.EnableRedirect = $false$wp.Url = "http://www.google.com"$wpm.SaveChanges($wp)$page.CheckIn("Test")$page.Publish("Test")$web.Close()$site.Close()

And that's it. The redirect is turned off, and it's been changed to point to Google. It's not a work of art, and a little cruddier than what I usually like to make my scripts, but I needed something quick and dirty to do the job. And that's what this does.

Retrieve the web.config modifications

The following powerhsell script will retrieve the web.cofig modifications for sharepoint Web application.

Script:

$webApp = Get-SPWebApplication -Identity http://sharepointsite
$webApp.WebConfigModifications

Get and Update the web property of a sharepoint site

The following powershell script updates the web properties of a sharepoint site.

Script:
$wa = get-spweb -identity "http://sharepointsite"
$wa.AllProperties["EmployeeListName"] = "Employees"
$wa.update();

Some times, the above script will not work, then i have used the below script to retrieve and update the web property.

Script:
$web = get-spweb 'http://sharepointsite'
$web.GetProperty('EmployeeListName')
$web.SetProperty('EmployeeListName', 'Employees')
$web.Update()

The following powershell script will retrieve the web properties,

Script:
$web = get-web  –identity  http://sharepointsite
$web.properties()
$web.AllProperties()

Update the Site Logo using PowerShell script

The following script updates the site logo url to the new url.

Script:
$sites=(get-spsite http://sharepointsite).AllWebs
$sites| foreach {
$var=$_.SiteLogoUrl;
if($var.Contains("http://testsite/"))
{
$var1=$var.Replace("http://testsite/", "http://newsite/");
$_.SiteLogoUrl = $var1;
$_.Update()
}
}

Update Primary and Secondary Site Collection Administrators using PowerShell script

The following script will update the Primary and Secondary Site collection administrators using powershell script. This script needs the Input as CSV file. And CSV file should contains the Sitecollectionurl,PrimaryAdmin,SecAdmin as columns.

Script:

#Get Site collection URL as a parameter  #param(  #[string] $filePath = $(Throw "Missing Input - CSV file path required with filename. Ex: C:\Solutions\SiteColAdmins.csv"), #required parameter  #[string] $LogFilePath = $(Throw "Missing Input - Path to create log file. Path al Ex: Ex: C:\Solutions\") #required parameter  #)  #Load SharePoint dll file  [void] [System.Reflection.Assembly]::Load(”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)
#Load SharePoint Snap In
cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
     Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
$filePath = "C:\Solutions\SiteColAdmins.csv"
$csv_info = Import-Csv $filePath
#Logfile Name and Path
$LogFilePath = "C:\Solutions\"
$date = (get-date).ToString('yyyyMMdd')
$FileName = "UpdatePrimarySecondaryAdmin"
$FileName = $LogFilePath += $FileName += $date
#Creating Log file
if(!(Test-Path -Path "$FileName.txt"))
{
$file = New-Item -type file "$FileName.txt"
}
Write-Host "--Begin Process--"
Add-Content -Path "$FileName.txt" -Value "Begin Process"
#iterate Csv File
foreach ($line in $csv_info)
{
Write-Host "--starting update for site: " $line.Sitecollectionurl " PrimaryOwner: " $line.PrimaryAdmin " & SecondaryOwner: " $line.SecAdmin
Add-Content -Path "$FileName.txt" -Value $( "--starting update for site: " + $line.Sitecollectionurl + " PrimaryOwner: " + $line.PrimaryAdmin + " and SecondaryOwner: " + $line.SecAdmin)
#Get site collection
$urltest=$line.Sitecollectionurl
$sadmin=$line.SecAdmin
$padmin=$line.PrimaryAdmin
if($urltest -ne $null)
{
if($sadmin -ne $null -or $sadmin -ne " ")
{
    if($padmin -ne $null -or $padmin -ne "")
    {
Set-SPSite -Identity $urltest -SecondaryOwnerAlias $sadmin -OwnerAlias $padmin
Write-Host "Primary owner :" $padmin "is successfully added to " $urltest
Add-Content -Path "$FileName.txt" -Value $("Primary owner: " + $padmin + "is successfully added to " + $urltest)
Write-Host "Secondary owner :" $sadmin "is successfully added to " $urltest
Add-Content -Path "$FileName.txt" -Value $("Secondary owner: " + $sadmin + "is successfully added to " + $urltest)
    }
else
{
Write-Host "Secondary owner :" $sadmin "is Empty and not added to " $urltest
Add-Content -Path "$FileName.txt" -Value $("Secondary owner: " + $sadmin + "is not added to " + $urltest)
}


}
else
{
Write-Host "Primary owner :" $padmin "is Empty and not added to " $urltest
Add-Content -Path "$FileName.txt" -Value $("Primary owner: " + $padmin + "is not added to" + $urltest)
}
}
}
Add-Content -Path "$FileName.txt" -Value "End Process"
Write-Host "--End Process--"

Get the Primary and Secondary Site collection Administrator using PowerShell script

The following script will generate the text file which will give the list of Primary & Secondary Site collection Administrators for each web application.

Script:

Add-pssnapin microsoft.sharepoint.powershell -EA 0
$outputFile = "C:\\SCAdminsReport.txt"
Write-Host "This script will loop through all site collections in a web application and list the collection's URL, Primary Owner, and Secondary Owner"
$webapp = "http://sharepointsite/"
$Web = Get-SPWebApplication $webapp
$text = ""
$text | out-file $outputFile
foreach ($sites in $Web.sites) {
    $text = "-------------------------------------------"
    $text | out-file $outputFile -append
        $text = "Site: " + $sites.url
        $text | out-file $outputFile -append
    $text = "Primary Owner: " + $sites.owner
        $text | out-file "$outputfile" -append
    $text = "Secondary Owner: " + $sites.secondarycontact
        $text | out-file "$outputfile" -append
    $text = "-------------------------------------------"
        $text | out-file "$outputfile" -append
    }
Write-Host "-----END------"