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

Thursday, April 7, 2016

Saving lookup meta data values to library using Powershell - SharePoint

When you take an item in a list, the Lookup fields store its value in the following format
id;#string

when programmatically adding meta data to a list's column the lookup value has to be built before assigning to the item field.

In the below example I refer one lookup, get its value/string. Using the string, do a search for the lookup list item id in the lookup list. Then create the new lookup field. Finally update item


  $myLookupItem = [Microsoft.SharePoint.SPFieldLookupValue]($_["FieldOne_InternalName"])
  $newLookupId = GetLookupId $myLookupItem.LookupValue

  $newLookupItem = New-Object Microsoft.SharePoint.SPFieldLookupValue($newLookupId  ,$myLookupItem.LookupValue)

$_["FieldTwo_InternalName"] = $newLookupItem

$_.Update()
$_.File.CheckIn(" FieldTwo value updated", 1)

$_ is explained in an earlier post

Wednesday, April 6, 2016

Query SharePoint Libraries using CAML query and Powershell

$web = Get-SPWeb $siteUrl
$list = $web.Lists[$listName]

1) Query items in list

if($list -ne $null)
{

$caml = '<OrderBy><FieldRef Name="ID" Ascending="True" /></OrderBy><Where><And> <Geq> <FieldRef Name="ID" /><Value Type="Number">{0}</Value> </Geq><Leq><FieldRef Name="ID" /><Value Type="Number">{1}</Value></Leq> </And> </Where> ' -f $startValue,$endValue

$myQuery = new-object Microsoft.SharePoint.SPQuery
$myQuery.Query = $caml

$filteredItems = $list.GetItems($myQuery)

$filteredItems | ForEach-Object {

      #Assign meta data to variables
      $variableOne = $_["MetaDataOne_InternalName"]
}

}

2) Remove specific items from list

if($list -ne $null)
{

$caml='<Where> <Or> <Or> <Or> <Eq> <FieldRef Name="Title" /><Value Type="Text">{0}</Value> </Eq> <Eq> <FieldRef Name="Title" /><Value Type="Text">{1}</Value> </Eq> </Or> <Eq> <FieldRef Name="Title" /><Value Type="Text">{2}</Value> </Eq> </Or> <Eq> <FieldRef Name="Title" /><Value Type="Text">{3}</Value> </Eq> </Or> </Where> ' -f $itemOne, $itemTwo, $itemThree, $itemFour

$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$col=$list.GetItems($query)

Write-Host 'Number of items removed: ' $col.Count

$col | % {$list.GetItemById($_.Id).Delete()}

}

$web.Dispose()

for more info about CAML query syntax visit here

Tuesday, April 5, 2016

Access User Profile Service using Powershell


function GetInfo([string]$userAccount)
{

 $mailAttribute = "WorkEmail"

 $mail = ""

 $serviceContext = Get-SPServiceContext -Site $siteUrl
 $profileManager =  New-Object  Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);

if($profileManager.UserExists($userAccount))
{
        $userProfile = $profileManager.GetUserProfile($userAccount)
        $mail = $userProfile[$mailAttribute].Value
}

return $mail
}

Get SharePoint user group and user details using Powershell

$SPWebCollection = $SPSite.AllWebs

$rootSite = $SPSite.RootWeb

foreach($SPGroup in $rootSite.Groups)
{
foreach($user in $SPGroup.users)
{
$users = new-object psobject
$users | add-member noteproperty -name "Group Name" -value $SPGroup.Name
$users | add-member noteproperty -name "User" -value $user
$users | add-member noteproperty -name "Display Name" -value $user.DisplayName

$email = GetInfo  $user
$users | add-member noteproperty -name "Work Email" -value $email
$combinedusers =[Array]$combinedusers + $users
}
}

        #Create CSV file
$filelocation=$filePath+"\"+$rootSite+".csv"
$combinedUsers | export-csv -path $filelocation -notype
$combinedUsers = $null

Friday, December 11, 2015

What happens when Enable-SPSessionStateService -DefaultProvision


Powershell command
Enable-SPSessionStateService -DefaultProvision 
The changes to the SQL server and web site are as follows:
1) SQL server
In the sql server a new Database will be created as 
"SessionStateService_706b1a65e15248618a0090cd50ed1823"
2) Web.config changesIn the web.config file he below entry is inserted

<system.web>
...
<sessionState mode="SQLServer" timeout="60" allowCustomSqlDatabase="true" sqlConnectionString="Data Source=shaamils_SqlServer;Initial Catalog=SessionStateService_706b1a75e15248618a0090cd60ed4813;Integrated Security=True;Enlist=False;Pooling=True;Min Pool Size=0;Max Pool Size=100;Connect Timeout=15" />
</system.web>

<modules runAllManagedModulesForAllRequests="true">
...
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
</modules>

Sunday, May 11, 2014

New Farm Administrator - could not be updated because the current user is not a farm administrator

You might have come across situations where a new farm administrator via the Central Admin, but the granted rights to the user account does not work as you expected.

In SharePoint 2010, even though a user is added as farm administrator, you might get an error in the log as "could not be updated because the current user is not a farm administrator".

This is due to the ShrarePoint 2010 security feature, which blocks modifications to any object inheriting from SPPersistedObject in the Microsoft.SharePoint.Administration namespace.

To resolve this issue, run the below script in powershell, which grants access.


function RemoteAdministrator-GiveAccess()                                                                                                
{                                                                                                                                                                 
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null                              
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $null       
                                                                                                                                                                   
    $contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService                        
    $contentService.RemoteAdministratorAccessDenied = $false                                                                   
    $contentService.Update()                                                                                                                        
}                                                                                                                                                                 
                                                                                                                                                                   
RemoteAdministrator-GiveAccess       




                                                                                                        

Sunday, February 16, 2014

Basic PowerShell for SharePoint and the Equivalent STSADM used in Earlier Version

This is a simple list down of basic PowerShell commands used in command line deployments in SharePoint. [SP 2010 and 2013]  &
The equivalent STSADM commands used in SharePoint 2007 ... back in the day ;)


1. Adding a new WSP to farm solution

SP 2010/2013 PowerShell
 Add-SPSolution -LiteralPath "C:\FolderName\Solution.wsp"
SP 2007 
Stsadm
 stsadm -o addsolution -filename "Solution.wsp"
[Assuming command runs from the correct folder location]


2. Deploy WSP 

SP 2010/2013 PowerShell
 Install-SPSolution -Identity "Solution.wsp" -WebApplication "http://WebSiteUrl" -CASPolicies -GACDeployment -Local -Force

AllWebApplications vs WebApplication - All allows the wsp to be deployed in all SP web applocations. WebApplication - allows the wsp to be deployed to a target web app
CASPolicies - Allows Code Access Security Policies to be deployed [optional]
GACDeployment - Allows DLL installation in the global assembly cache [optional]
Force [optional]
Local - Deploys only in the current server [optional]
SP 2007 
Stsadm
stsadm -o deploysolution -name "SolutionName" -url "Site URL" -immediate -allowgacdeployment -allowcaspolicies -force

instead of -url, you can use -allcontenturls 
instead of -immediate, you can use -time "time to deploy"

GACDeployment - Allows DLL installation in the global assembly cache [optional]


3. Activate feature

SP 2010/2013 PowerShell
 Enable-SPFeature –identity "FeatureName" -URL http://WebSiteUrl
SP 2007 
Stsadm
 stsadm -o activatefeature -id feature_ID -url http://WebSiteUrl -force
[Instead of -Id, you can use -filename or -name with appropriate values]



4. De-activate feature

SP 2010/2013 PowerShell
 Disable-SPFeature –identity "FeatureName" -URL http://WebSiteUrl
SP 2007 
Stsadm
stsadm -o deactivatefeature -id feature_ID -url http://WebSiteUrl
[Instead of -Id, you can use -filename or -name with appropriate values]



5. Retract WSP 

SP 2010/2013 PowerShell
Uninstall-SPSolution -Identity "Solution.wsp" -WebApplication http://WebSiteUrl
SP 2007 
Stsadm
stsadm -o retractsolution -name "Solution.wsp" -url http://WebSiteUrl -immediate 
[Instead of -immediate, you can use -time "TimeToRun"]



6. Remove WSP from SharePoint farm

SP 2010/2013 PowerShell
Remove-SPSolution -Identity "Solution.wsp"
SP 2007 
Stsadm
stsadm -o deletesolution -name "Solution.wsp"

Saturday, October 26, 2013

Get-SPWebApplication is not recognised as the name of the cmdlet

When you try to execute SharePoint specific commands through PowerShell, might come across a message

"Get-SPWebApplication is not recognized as the name of the cmdlet ......"

The SP specific commands are not being recognized in PowerShell at this point. Adding a snap in would do the trick. Type the below command in your PowerShell  window.

Add-PSSnapin Microsoft.Sharepoint.Powershell

That's it. Provided that the rights in DB are there, you should be able to execute SharePoint based commands now.