Subscribe:

Labels

Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Wednesday, August 12, 2020

List All WebParts

 #----------------------------------------------------------------------------- 

# Name:             list-all-webparts.ps1  

# Description:      This script will create a list of all web parts in all 

#                   pages in a site collection.

#                     

# Usage:            Run the script passing three paramters: Url, Folder and WP. 

# Url Accepts multiple values (comma separated).

#                   Folder is the destination of the report.

# WP is the name of the web part (optional).

# By:               Riccardo Celesti blog.riccardocelesti.it

#----------------------------------------------------------------------------- 



Param([Parameter(Mandatory=$true)] 

      [String] 

      $Url,

      [Parameter(Mandatory=$true)] 

      [ValidateScript({Test-Path $_ -PathType 'Container'})]

      [String] 

      $folder,

  [Parameter(Mandatory=$false)]

      [String] 

      $WP


if ((gsnp Microsoft.SharePoint.Powershell -EA SilentlyContinue) -eq $null){

    asnp Microsoft.SharePoint.Powershell -EA Stop

}


$filename = "WebPartsReport_" + (Get-Date).ToFileTimeUtc().ToString() + ".csv"

$filenamewp = "WebPartsReport_" + $WP.Replace(" ","-") + "_" + (Get-Date).ToFileTimeUtc().ToString() + ".csv"


$logfile = Join-Path $folder $filename

$logfilewp = Join-Path $folder $filenamewp


$urlArray = $Url.Split(",")


$header = "File Url, Web Part Title, Web Part Type, Visible"


ac $logfile $header

ac $logfilewp $header


$logfilecontrol = $null


foreach ($SPsite in $urlArray){

    Get-SPSite $SPsite| % {


        foreach ($web in $_.AllWebs){

        

            if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web)){


                $library = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)

                $pages = $library.PagesList

            

                foreach ($file in $pages.Items){


                    $fileUrl = $web.Url + "/" + $file.File.Url


                    $manager = $file.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);


                    $webparts = $manager.webparts


                    $webparts | %{

                        ac $logfile "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"

if ($_.DisplayTitle -match $WP -and -not [string]::IsNullOrEmpty($WP)){

ac $logfilewp "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"


                            $logfilecontrol = 1

}

                    }

                }


                $sitepages = [Microsoft.Sharepoint.Utilities.SpUtility]::GetLocalizedString('$Resources:WikiLibDefaultTitle',"core",$web.UICulture.LCID)


                $pages = $null

                $pages = $web.Lists[$sitepages]


                if ($pages -and $pages.ItemCount -gt 0){


                    foreach ($file in $pages.Items) {

                        $fileUrl = $web.Url + "/" + $file.File.Url


                        $manager = $file.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);


                        $webparts = $manager.webparts


                        $webparts | %{

                            ac $logfile "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"

if ($_.DisplayTitle -match $WP -and -not [string]::IsNullOrEmpty($WP)){

ac $logfilewp "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"


                                $logfilecontrol = 1

}

                        }   

                    }

                }

            } else {

                $sitepages = [Microsoft.Sharepoint.Utilities.SpUtility]::GetLocalizedString('$Resources:WikiLibDefaultTitle',"core",$web.UICulture.LCID)


                $pages = $null

                $pages = $web.Lists[$sitepages]


                if ($pages){


                    foreach ($file in $pages.Items) {

                        $fileUrl = $web.Url + "/" + $file.File.Url


                        $manager = $file.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);


                        $webparts = $manager.webparts


                        $webparts | %{

                            ac $logfile "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"

                            

                            if ($_.DisplayTitle -match $WP -and -not [string]::IsNullOrEmpty($WP)){

ac $logfilewp "$fileUrl, $($_.DisplayTitle), $($_.GetType().ToString()), $($_.IsVisible)"


                                $logfilecontrol = 1

}

                        }

                    }

                }

            }

        }

    }

}


notepad.exe $logfile


if ($logfilecontrol -eq 1){

    notepad.exe $logfilewp

}

Detect and Remove inactive AD Accounts

 #Powershell to Remove Orphaned Users from SharePoint 2013/2010


#Load SharePoint Management shell 

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {

    Add-PSSnapin "Microsoft.SharePoint.PowerShell"

}

 

#Function to Check if an User exists in AD

function CheckUserExistsInAD()

   {

   Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )

   

  #Search the User in AD

  $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

  foreach ($Domain in $forest.Domains)

  {

         $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Domain.Name)

         $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)

     

         $root = $domain.GetDirectoryEntry()

         $search = [System.DirectoryServices.DirectorySearcher]$root

         $search.Filter = "(&(objectCategory=User)(samAccountName=$UserLoginID))"

         $result = $search.FindOne()

  

         if ($result -ne $null)

         {

           return $true

         }

  }

  return $false 

 }

  

 #Change these variables as desired

 #$WebAppURL="http://SharePointWebSite"

 #$RemoveUsers = $false

  

  

  

    

 #Get all Site Collections of the web application

 #$WebApp = Get-SPWebApplication $WebAppURL

$textout = ""

 $textout > "D:\SPO\SharePointOrphanedUsers.csv"

$Farm = Get-SPWebApplication

Foreach ($WebApplicationname in $Farm)

    {

    $WebApp = Get-SPWebApplication -identity $WebApplicationname

    $WebAppSites = $WebApp.Sites

  

 #Iterate through all Site Collections

 foreach($site in $WebApp.Sites)  

 {

    if ($site -ne $null)

    {

        $web = $site.AllWebs

        foreach ($webp in $web)

        {

            $OrphanedUsers = @()

            if (($webp.permissions -ne $null) -and ($webp.hasuniqueroleassignments -eq "True"))

            {

                #Iterate through the users collection

                foreach($User in $webp.SiteUsers)

                {

                    #Exclude Built-in User Accounts , Security Groups & an external domain "corporate"

                    if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and

                            ($User.LoginName.ToLower() -ne "nt authority\system") -and

                                ($User.LoginName.ToLower() -ne "sharepoint\system") -and

                                  ($User.LoginName.ToLower() -ne "nt authority\local service")  -and

                                      ($user.IsDomainGroup -eq $false ) -and

                                          ($User.LoginName.ToLower().StartsWith("corporate") -ne $true) )

                    {

 

                        $UserName = $User.LoginName.split("\")  #Domain\UserName

                        $AccountName = $UserName[1]    #UserName

                         

                        #If the user does not exist in Active Directory then it is an orphaned account in the SharePoint Site Collection

                        if ( ( CheckUserExistsInAD $AccountName) -eq $false )

                        {

                                $textout = """$($User.Name)"",""$AccountName"",""($($User.LoginName))"",""$($webp.URL)"""

                                #Write-Host $textout

                                $textout >> "D:\SPO\SharePointOrphanedUsers.csv"

                                #Make a note of the Orphaned user

                                $OrphanedUsers+=$User.LoginName

                                 

                                 

                        }

                         

                    }

                }

                # ****  Remove Users ****#

                # Remove the Orphaned Users from the site

              #  if ($RemoveUsers)

                #{

                   # foreach($OrpUser in $OrphanedUsers)

                    #{

                       # $webp.SiteUsers.Remove($OrpUser)

                       # Write-host "Removed the Orphaned user $($OrpUser) from $($webp.URL) "

                    #}

               # }

 

            }

 

        }        

                  

    }

}

    }

Thursday, September 27, 2018

Clear sharepoint cache


## SharePoint Server 2013: PowerShell Script To Reset The Config Cache On All Servers In A Farm ##


Add-PSSnapin Microsoft.SharePoint.PowerShell
$Servers = Get-SPServer | ? {$_.Role -ne "Invalid"} | Select -ExpandProperty Address
Write-Host "This script will reset the SharePoint config cache on all farm servers:"
$Servers | Foreach-Object { Write-Host $_ }
Write-Host "Press enter to start."
Read-Host
Invoke-Command -ComputerName $Servers -ScriptBlock {
    try {
        Write-Host "$env:COMPUTERNAME - Stopping timer service"
        Stop-Service SPTimerV4
        $ConfigDbId = [Guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\15.0\Secure\ConfigDB' -Name Id).Id #Path to the '15 hive' ConfigDB in the registry
        $CacheFolder = Join-Path -Path ([Environment]::GetFolderPath("CommonApplicationData")) -ChildPath "Microsoft\SharePoint\Config\$ConfigDbId"
        Write-Host "$env:COMPUTERNAME - Clearing cache folder $CacheFolder"
        Get-ChildItem "$CacheFolder\*" -Filter *.xml | Remove-Item
        Write-Host "$env:COMPUTERNAME - Resetting cache ini file"
        $CacheIni = Get-Item "$CacheFolder\Cache.ini"
        Set-Content -Path $CacheIni -Value "1"
        }
    finally{
        Write-Host "$env:COMPUTERNAME - Starting timer service"
        Start-Service SPTimerV4
        }
}


Add Server to SP Farm



Add-PSSnapin Microsoft.SharePoint.Powershell
cls
# Farm configuration
$config_Passphrase = "Rcsp2013"
$s_config_Passphrase = (ConvertTo-SecureString -String $config_passphrase -AsPlainText -force)

$server_DB = "NETSHPTSQL"
$db_Config = "SP2013_Configuration"
$db_CentralAdmin = "SP2013_Content_CentralAdministration"
$ca_port = 55555
$ca_AuthProvider = "NTLM"

########################################
# Add the Server to the farm

Write-Output "Adding the Server $db_Config"
Connect-SPConfigurationDatabase -DatabaseName $db_Config -DatabaseServer $server_DB -Passphrase  $s_config_Passphrase
#-FarmCredentials $accounts.farm.credential

Write-Output "Install Help Collections"
Install-SPHelpCollection -All
Write-Output "Initialize security"
Initialize-SPResourceSecurity
Write-Output "Install services"
Install-SPService
Write-Output "Register features"
Install-SPFeature -AllExistingFeatures
Write-Output "Install Application Content"
Install-SPApplicationContent
Write-Output "Get-SPFarm | select Servers"
Get-SPFarm | select Servers


Wednesday, February 8, 2012

SPDisposeCheck for SharePoint development


SPDisposeCheck is  tool that helps to developers and administrators check the custom SharePoint solutions that use the SharePoint Object Model helping measure against known Microsoft dispose best practices. This tool may not show all memory leaks in your code and may produce false positives which need further review by subject matter experts.

The SPDisposeCheck updated tool remains a standalone command line utility and have been added to a Visual Studio 2008/2010 IDE Add-In which calls out to the SPDisposeCheck.  This Add-In was originally presented at the SPC 2009 and is now available publically.  In addition this version has been tested with both WSS 3.0 + MOSS 2007 and SharePoint 2010 (Foundation and Server) environments.

Finally, it is encouraged you to run the updated SPDisposeCheck tool on all customized SharePoint projects to help identify areas in code which may lead to memory pressure and server stability issues.  As a best practice you should consider adding this tool to your SharePoint software development life cycle build process and review its output with a subject matter expert on a regular interval.
Enhanced by Zemanta