Hello,
Here is an example of PowerShell function for page to check if the web part exists on it.
function IsWebPartExist($siteUrl, $pageUrl ,$WPName,$WPEmailReport){
$wpExists = $false
try{
$spSite = Get-SPSite $siteUrl -ErrorAction:Stop
if($spSite -eq $null){return;}
$spWeb = $spSite.OpenWeb()
$spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
foreach ($webpart in $spWebPartManager.WebParts)
{
if ($webpart.GetType().Name -eq $WPName)
{
$wpExists = $true
return $true
}
}
}
catch{
$WPEmailReport += New-Object PSObject -Property @{PageURL=$siteUrl;Status="$_.Exception.Message";}
}
finally{
$spWeb.Dispose()
$spSite.Dispose()
}
return $wpExists
}
Invoke the function
$CurDir = Split-Path -parent $MyInvocation.MyCommand.Definition
$WPEmailReport = @()
$url = "http://yourpage"
$isSiteWebExists = Get-SPSite $url -ErrorAction:SilentlyContinue
$web = $isSiteWebExists.RootWeb;
$folder = $web.RootFolder;
$isWelcomePageExists = $folder.WelcomePage
$landingPage = $isWelcomePageExists
$isWebPartPDEsist = IsWebPartExist -siteUrl $url -pageUrl $landingPage -WPName "PublishedDocuments" -WPEmailReport $WPEmailReport
if ($isWebPartPDEsist -eq $true)
{ $WPEmailReport += New-Object PSObject -Property @{PageURL=$url};}
Write-Host "Writing log files...."
$TimeString = Get-Date -format MM_dd_yyyy__HH_mm
$WPEmailReport | select-object PageURL | Export-csv -path "$CurDir\PDWebPartExist_$TimeString.csv" -notype
Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts
Tuesday, January 21, 2014
Friday, January 17, 2014
Powershell single-object arrays
If function return a single-object arrays you won't have a Count method in Powershell array.Count
- A function that returns an array with a single value might not be seen as an array to the code calling it. Because of rule one, you can still iterate over it, but it won’t have array properties such as Count.
- If you want to guarantee that you get an array from a function, wrap the call with @().
Example 1: In this case $allPubPages variable with have type string.
$allPubPages=@()
$allPubPages = GetAllSitePublishingPages -url $url
Example 2 In this case $allPubPages variable will have type array:
$allPubPages=@()
$allPubPages = @(GetAllSitePublishingPages -url $url)
Function:
function GetAllSitePublishingPages($url){
$pageArray = @()
filter Get-PublishingPages {
$pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($_)
$query = new-object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$pubweb.GetPublishingPages($query)
}
if($leave){return $pageArray}
try{
get-spweb $url -ErrorAction:SilentlyContinue | Get-PublishingPages |%{
$pageArray += $_.Uri.ToString()
}
}
catch{
return $pageArray
}
#write-host $pageArray
return $pageArray
}
Good luck.
Friday, December 27, 2013
SharePoint 2010 Document Property Promotion and Demotion
The Case of the Missing Office Document Properties in SharePoint 2010
Nice article about Document Property Promotion and Demotion
Property promotion is the functionality in WSS that pulls the document metadata (e.g. Title, Subject, etc) from Office 2003/2007/2010 documents during upload and sets those values to their corresponding column in WSS. Property demotion is just the opposite, if you update the document properties (like Title) via the WSS UI that property value is written back to the file.
Basically, with property promotion/demotion, we keep the properties in the document and in WSS in sync.
More info
http://msdn.microsoft.com/en-us/library/office/aa543341(v=office.14).aspx
Wednesday, December 18, 2013
Enable/disable output caching in SharePoint 2010 using PowerShell script
A SharePoint Publishing site can also be configured to make use of the ASP.NET output cache to store rendered ASPX pages in memory. You can only make use of this cache when the Publishing features are activated on your site collection. This means that only publishing pages can be cached.
When a Publishing page is first requested, SharePoint assembles the page dynamically: it first fetches the page layout from the content database and then fetches the contents of the page. The page layout comes from the content database; the data on the page can be data coming from the content database or files already cached in the BLOB cache. Once the page is assembled, the resulting HTML stream is stored in the output cache. On a next request the HTML is served from the cache: the controls are not created, the page life cycle doesn’t start, and no code-behind is executed. The only things that are not covered by the output cache, are images and other resources like JavaScript files and CSS files. These need to be handled by other caching mechanisms.
This way pages are served more quickly and CPU load is reduced on the web front-end servers and on the SQL Server content database because pages won’t have to be reassembled on each request. Output caching is considered as one of the most performance improving techniques.
Here a a link to original article about Output Caching.
Here is a PowerShell script to enable or disable on output caching in SharePoint 2010 site:
$TotalCount = 0;
$UpdatedCount = 0;
#Initiate array for output export
$Results=@();
function SetCacheSettingsOnSite($site)
{
if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($site.RootWeb))
{
$cacheSettings
= new-object
Microsoft.SharePoint.Publishing.SiteCacheSettingsWriter($site.Url);
if($disable -eq
$true)
{
if($cacheSettings.EnableCache
-eq $true)
{
$cacheSettings.EnableCache
= $false;
$cacheSettings.SetAnonymousPageCacheProfileId($site,1);
$cacheSettings.SetAuthenticatedPageCacheProfileId($site,1);
$cacheSettings.Update()
if($output -eq $true) {Write-Host "De-activated
output cache on site $site"}
Set-Variable -Name UpdatedCount -Value
($UpdatedCount+1) -Scope 1;
$OutputLog =
New-Object PSObject
-Property @{SiteUrl=$site.Url;Status="Deactivated";Time=Get-Date}; Set-Variable -Name Results -Value
($Results+=$OutputLog) -Scope
1;
}
else
{
if($output -eq $true) {Write-Host "Output
cache already de-actived on site $site"}
$OutputLog =
New-Object PSObject
-Property @{SiteUrl=$site.Url;Status="Skipped.
Already De-Activated";Time=Get-Date}; Set-Variable
-Name Results
-Value ($Results+=$OutputLog)
-Scope 1;
}
}
else
{
if($cacheSettings.EnableCache
-eq $false)
{
$cacheSettings.EnableCache
= $true;
$cacheSettings.EnableDebuggingOutput
= $true;
$cacheSettings.SetAnonymousPageCacheProfileId($site,1);
$cacheSettings.SetAuthenticatedPageCacheProfileId($site,4);
$cacheSettings.SetFarmCacheFlushFlag();
$cacheSettings.Update();
if($output -eq $true) {Write-Host "Activated
output cache on site $site"}
Set-Variable -Name UpdatedCount -Value
($UpdatedCount+1) -Scope 1;
$OutputLog =
New-Object PSObject
-Property @{SiteUrl=$site.Url;Status="Activated";Time=Get-Date}; Set-Variable -Name Results -Value
($Results+=$OutputLog) -Scope
1;
}
else
{
if($output -eq $true) {Write-Host "Output
cache already active on site $site"}
$OutputLog =
New-Object PSObject
-Property @{SiteUrl=$site.Url;Status="Skipped.
Already active";Time=Get-Date}; Set-Variable
-Name Results
-Value ($Results+=$OutputLog)
-Scope 1;
}
}
}
$site.Dispose();
}
$Results | select-object SiteUrl, Status, Time | Export-csv -path "CachingActivationResults.csv"
-notype
Write-Host "Done.
Updated:$UpdatedCount Total Processed:$TotalCount" -ForegroundColor
Green
$rootSite.Dispose()
Thursday, November 21, 2013
ERROR : Exception calling "AddWebPart" with "3" argument(s): "The file is not checked out. You must first check out this document before making changes
When you try to add web part on the page using SPLimitedWebPartManager AddWebPart function you get the following error:
ERROR : Exception calling "AddWebPart" with "3" argument(s): "The file is not checked out. You must first check out this document before making changes
The error appears when the page is checked out AFTER the SPLimitedWebPartManager is
retrieved.
....................................................
$spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$page.CheckOut()
....................................................
So the page must be checked out BEFORE the SPLimitedWebPartManager is retrieved.
$page.CheckOut()
$spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
Monday, August 12, 2013
Exception setting „Hidden” Cannot change Hidden attribute for this field”
Requirements:
Requirements was to remove the Taxonomy field „Parent Company” from the Sharepoint List as this field is not used by anyone.
Issue:
Issue with the „Parent Company” field deleting with PowerShell script. After the script run the following error message has appeared. „Exception setting „Hidden” Cannot change Hidden attribute for this field”
Investigation:
This is an internal issue in SharePoint2010.
The common issue description can be found here: http://blogs.msdn.com/b/spblog/archive/2013/04/27/sps2010-field-cannot-be-made-again-visible-if-defined-to-be-hidden-using-visual-studio-2010.aspx .
During development the field „Parent Company” was created usisng xml definition in Visual Studio 2010 and a field attribute „Hidden” was set to value „True” (true if the field is hidden; otherwise, false.)
To be possible to change property Hidden to false, the property „CanToggleHidden” value should be set to True in a field definition, the way like in this example below (but in this case the property is absent at all in the field definition).
Solution:
Solution was found to use reflection to change property „CanToggleHidden” value to True, cahnge Hidden property to false and delete the field from the List via PowerShell
PowerShell example:
Requirements was to remove the Taxonomy field „Parent Company” from the Sharepoint List as this field is not used by anyone.
Issue:
Issue with the „Parent Company” field deleting with PowerShell script. After the script run the following error message has appeared. „Exception setting „Hidden” Cannot change Hidden attribute for this field”
Investigation:
This is an internal issue in SharePoint2010.
The common issue description can be found here: http://blogs.msdn.com/b/spblog/archive/2013/04/27/sps2010-field-cannot-be-made-again-visible-if-defined-to-be-hidden-using-visual-studio-2010.aspx .
During development the field „Parent Company” was created usisng xml definition in Visual Studio 2010 and a field attribute „Hidden” was set to value „True” (true if the field is hidden; otherwise, false.)
<Field
ID="{747FC1CF-FCED-44EB-B895-568E9F423174}"
Name="ALLegalCompanyTaxHTField1"
StaticName="ALLegalCompanyTaxHTField1"
Type="Note"
Overwrite="TRUE"
RowOrdinal="0"
DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
Hidden ="TRUE">
</Field>
An taxonomy
field consists of two fields (example:
„Parent Company” can be seen
on screenhot)
The „Parent Company” is a taxonomy field
and consists of two fields
definition ALLegalCompany and ALLegalCompanyTaxHTField1
<Field
ID="{B5FE2B9E-CDF9-4B4A-B34C-85650481A280}"
Name="ALLegalCompany"
StaticName="ALLegalCompany"
Type="TaxonomyFieldType"
ShowField="Term1033"
Overwrite="TRUE"
Mult="TRUE"
DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
Hidden ="FALSE">
</Field>
The field ALLegalCompany has „Hidden” proeprty set value
to False.
The field ALLegalCompanyTaxHTField1 has property
„Hidden” set to True that caused
the difficulties to delete this field.
Fields in SharePoint can be added
using xml definition via Visual Studio, but cannot be delete
that way, therefore the Powershell
commands must be used to delete
fields from Lists or Content
Type. But the field „Parent
Comapny” cannot be deleted that’s
way using scrips, because fields should be
visible and property „Hidden” is set to false. Property
„Hidden” cannot be set
to false, because this property depends
(relies) on other property called „CanToggleHidden” and it’s value should
be set to True. „CanToggleHidden” property is Read-only
and and it’s value cannot
be change directly, because there is no setter
method (this is a SharePoint property that stored in
native assemly (SPField) and was
developed that way, the reason
of that fact
is unknown).To be possible to change property Hidden to false, the property „CanToggleHidden” value should be set to True in a field definition, the way like in this example below (but in this case the property is absent at all in the field definition).
<Field
ID="{747FC1CF-FCED-44EB-B895-568E9F423174}"
Name="ALLegalCompanyTaxHTField1"
StaticName="ALLegalCompanyTaxHTField1"
Type="Note"
Overwrite="TRUE"
RowOrdinal="0"
DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
Hidden ="TRUE"
CanToggleHidden ="TRUE">
</Field>
By default CanToggleHidden is return false as
it is not presented in the
definition. Adding the property and
deploy solution don’t change the
field defintion.
If we have a look in
code at the
„Hidden” property setter in assembly Microsoft.SharePoint.SPField
it also sets „CanToggleHidden”
property to true, but cannot be
reached because it is value by
default is false and throw
the error message shown in
the picture above „Exception
setting „Hidden” Cannot change Hidden
attribute for this field”. |
this.SetFieldBoolValue("CanToggleHidden", true)
|
[ClientCallable]
public bool Hidden
{
get
{
if (this.HasExternalDataSource)
{
return SPExternalList.IsFieldHidden(this);
}
return this.GetFieldBoolValue("Hidden",
4);
}
[ClientCallableExceptionConstraint(FixedId="1",
ErrorCode=-2146232832, Condition="Thrown when attempting to set Hidden property
for a field that does not
allow this property to be toggled.", ErrorType=typeof(SPException))]
set
{
if (!this.CanToggleHidden)
{
throw new
SPException(SPResource.GetString("HiddenAttributeUpdateNotAllowed",
new object[0]));
}
this.SetFieldBoolValue("Hidden",
value);
this.SetFieldBoolValue("CanToggleHidden", true);
}
}
Solution:
Solution was found to use reflection to change property „CanToggleHidden” value to True, cahnge Hidden property to false and delete the field from the List via PowerShell
PowerShell example:
$web = Get-SPWeb "http://sharepoint/
$listLegComp = $web.Lists["YourList"]
$pcFieldTax = $listLegComp.Fields.GetFieldByInternalName("ALLegalCompanyTaxHTField1")
$pcField = $listLegComp.Fields.GetFieldByInternalName("ALLegalCompany")
if(!$pcFieldTax.CanToggleHidden)
{
$bindingFlags = [Reflection.BindingFlags] "NonPublic,Instance"
[System.Type] $type = $pcFieldTax.GetType()
[Reflection.MethodInfo] $mdInfo = $type.GetMethod("SetFieldBoolValue",$bindingFlags)
$object = [System.Object] @("CanToggleHidden",$true)
$mdInfo.Invoke($pcFieldTax,$object)
$pcFieldTax.Hidden = $false
$pcFieldTax.AllowDeletion = $true
$pcFieldTax.Update()
}
if(!$pcField.CanToggleHidden)
{
$bindingFlags = [Reflection.BindingFlags] "NonPublic,Instance"
[System.Type] $type = $pcField.GetType()
[Reflection.MethodInfo] $mdInfo = $type.GetMethod("SetFieldBoolValue",$bindingFlags)
$object = [System.Object] @("CanToggleHidden",$true)
$mdInfo.Invoke($pcField,$object)
$pcField.Hidden = $false
$pcField.AllowDeletion = $true
$pcField.Update()
}
$pcFieldTax.Delete()
$pcField.Delete()
$listLegComp.Update()
$web.Dispose()
Subscribe to:
Posts (Atom)