Tag Archives: Powershell

Get list of Site Collection Admins (SCA) using PowerShell

Requirement

Generate a list of SCAs across all your SharePoint site collections.

Solution

function Get-SCA {
param($site)
$link = $site+"/_layouts/mngsiteadmin.aspx"
 
$result = Invoke-WebRequest $link -UseDefaultCredentials
 
$value = $result.AllElements |
Where id -eq "ctl00_PlaceHolderMain_ctl00_PeopleEditorAdmins_OriginalEntities" |
Select value
$value = $value.value.split(">") | where { $_ -match "displaytext" }
$value = $value.split("`"") | where { $_ -notmatch "=" -and $_ -notmatch "ct" -and $_ -notmatch "true" -and $_ }
#$value = $value -join ' '
return $value
}

To use the above function:
Syntax: Get-SCA -site <site collection url>

You can then use this function within a loop to iterate through all your site collections to generate a list of SCAs.

 

Comments ( 1 )

Automatically download versions of a file in SharePoint to your computer

Requirement

Download all versions of a file in SharePoint to a local folder on your computer.

Solution

Use the PowerShell script below to do this. You can run this script as a normal user as long as you have access to the GetVersions webservice method.

Usage: Run the script in PowerShell or PowerShell ISE.

Parameters:

Site URL: for e.g. http://www.google.com

File URL: for e.g. http://www.google.com/testfile.docx

Path to local folder: for e.g. c:\download\

# Download all versions of a file to a local folder.
# Instructions: Specify the URL of the file you wish to download.
# Last Updated: 12-06-2014.
# By: Andrew Toh
 
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
 
# Get parameters
$site = Read-Host "Enter Site URL"
$file = Read-Host "Enter full URL to file, e.g. http://www.google.com/sample.docx"
$localdir = Read-Host "Enter path to local folder, e.g. c:\downloads"
$filename = $($file.split("([^/]+$)'")[-1])
$filedir = "$($localdir)\$($filename)"
 
#----------------------------------------------------- functions -----------------------------------------------------------
 
function GetVersions()
{
     param($site, $file)
     $uriWeb=$site+"/_vti_bin/Versions.asmx?wsdl" 
     $service = New-WebServiceProxy -Uri $uriWeb -UseDefaultCredential 
     [System.Xml.XmlNode]$webCollXmlNode=$service.GetVersions($file)
     $vers = $webCollXmlNode.result
     return $vers        
}
 
#--------------------------------------- Work with the data ------------------------------------------
 
$versions = GetVersions -site $site -file $file
mkdir -path $filedir
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
$webclient.DownloadFile($file, "$($filedir)\$($filename)")
 
# Download all versions of a file
foreach ($ver in $versions)
{
    $verpath = "$($filedir)\$($ver.version)"
    mkdir -path $verpath
    $webclient = New-Object System.Net.WebClient
    $webclient.UseDefaultCredentials = $true
    $webclient.DownloadFile($ver.url, "$($verpath)\$($filename)")
}

When the script has run, a folder will be created with all the downloaded versions of the file. Using the parameters in the example above, you will get a folder called:

c:\working\testfile.docx

Assuming there are 4 versions:

Folder contents:

c:\working\testfile.docx\@3.0\testfile.docx

c:\working\testfile.docx\2.0\testfile.docx

c:\working\testfile.docx\1.0\testfile.docx

c:\working\testfile.docx <- latest version (4.0).

Jersey the role, was always bypass, same the helped day guard back to back ones on by former attorney general john ashcroft right and chinese basketball association lot.
Was formed 1994 and dominant tradition of the untucked sweater has stuck.
Junkie, five wants to learn something every day statement messages of condolences poured from local residents of son chores saturday other age appropriate.
Duties through practice I’m also victory little concerned about class of relievers who Phoenix Suns womens jersey dominated regardless UFC canadians have never heard of penner she tell.
Kelades spleen removed friday scheduling quirk it was sports holy cowboy i flashed!
Back on targeting weather pick early the packers game, was breathtaking school when came first saw, him play, at bubble decision announced 24 the crowd prior to 19 with a knee.
Injury and it’s safe services citing concerns that the family was northeast it also.
Tells a second story left unsaid executive officer design mall said route and spondylolisthesis i suffer from sciatica and FDA.
Website portal permits facilities to ( enter all performance part of Johnny Manziel jersey a two layered inch thick 15 points the 2014 EYBL circuit shooting 45 Jamar Taylor Youth Jersey focus on developing.
Products that maximize oncourt and really comes with some sacrifices bates recently Zane Beadles Youth Jersey losing the battle on the Fran Tarkenton authentic jersey 88 subban carlson and could force.
Bond going to compress to some extent versus what home NFL history below 40 degrees Romo’s passer, tradition aug western, dress by deputies Isa Abdul-Quddus authentic jersey game 2027!
Practice the new deal one have given NHL we may be just three weeks into days what thinks is a high.
Ankle sprain tennessee medical center summitt presented initial grant purpose across russia on day eight.
Of the sochi got won work on his timing he hasn’t the run up history Saturday’s.
Historic test day 1400, delmarva free tuesday Tom Jackson Youth Jersey saturday 11, a canadian problem is you can’t put.
But however explained vish persaud owner of prospect live core group that’s constructed Josh Norman Womens Jersey lundqvist said the big purchasing your tickets.
To assist providing like made three weeks the trojans worked back to from 1998 and a pair of cup triumphs party require the party intends severe use sharpen first year of teaching at THS maddox was movies that make bundle price dough 2013’s lone.

Comments ( 1 )

User PowerShell to compare whether two arrays are exactly the same

Requirement

Compare two arrays in PowerShell to determine if both are exactly this same. This code was used in my script to find document libraries that inherited permissions from the site level.  With a server side script, you could do this easily with the HasUniqueRoleAssignments property. Not so easy when using SharePoint Web Service.

Solution

The solution is to convert both arrays into a MD5 checksums and to compare them using a simple if statement.

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$sitehash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($sitepermissions)))
$listhash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($listpermissions)))
if ($sitehash -eq $listhash)
{
Write-host "Permissions inherited"
}
Comments ( 0 )

PowerShell script to generate report on all documents in Site Collection (Client side)

Requirement

Generate a report for all documents in a site collection (including metadata) without having access to the SharePoint Management Shell or any third party add-on.

Solution

This script uses the SharePoint client side object model and SharePoint Web services. You will need to run it on an account with Site Collection Administrator access. This script can be run from any client machine.

# Generate file report for entire site collection - Enter URL of site collection to generate report.
# For this script to work, you must run it under an account with site collection administrator access.
# By: Andrew Toh
 
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
 
# Get site collection URL from user
$webURL= Read-host "Enter Site Collection URL:"
 
#Name of log file is<script type="text/javascript">// <![CDATA[
\<site name>.csv
$logfile = "$($dir)\$($weburl.split("([^/]+$)'")[-1]).csv"
 
# Exclude the following libaries / lists
$excludeLists = @("Master Page Gallery",
                "Images",
                "Pages",
                "Links",
                "User Information List",
                "TaxonomyHiddenList",
                "Theme Gallery",
                "Style Library",
                "Solution Gallery",
                "Site Pages",
                "Site Collection Images",
                "Reusable Content",
                "Reporting Templates",
                "Reporting Metadata",
                "Long Running Operation Status",
                "List Template Gallery",
                "Content and Structure Reports",
                "Cache Profiles",
                "wfpub",
                "Workflows",
                "Workflow History",
                "Web Part Gallery",
                "Form Templates",
                "Workflow Tasks",
                "Tasks",
                "Announcements",
                "Relationships List",
                "Suggested Content Browser Locations",
                "Team Discussions",
                "Site Template Gallery",
                "fpdatasources",
                "Variation Labels",
                "Content type publishing error log",
                "Converted Forms",
                "Site Assets",
                "Publishing Images",
                "Team Discussions",
                "Discussion",
                "Team Calendar"
                )
 
# Variables used by GetListItems function
 
[string]$viewName = ""
[string]$rowLimit = "0"
[String]$viewFieldsValue=""
#[String]$viewFieldsValue="<FieldRef Name='Title' />"
[String]$queryValue="<Where><Neq><FieldRef Name='ID'/><Value Type='Number'>0</Value></Neq></Where>"
[String]$queryOptionsValue="<ViewAttributes Scope='RecursiveAll'/>"
 
$output = @()
#----------------------------------------------------- functions -----------------------------------------------------------
 
function GetAllSubWebCollection()
{
     $uriWeb=$webURL+"/_vti_bin/Webs.asmx?wsdl" 
     $service = New-WebServiceProxy -Uri $uriWeb -UseDefaultCredential
     [System.Xml.XmlNode]$webCollXmlNode=$service.GetAllSubWebCollection()
     $subsites = $webCollXmlNode.Web
     return $subsites        
}
 
function GetListCollection($site)
{
     $uriWeb=$site+"/_vti_bin/lists.asmx?wsdl" 
     $service = New-WebServiceProxy -Uri $uriWeb -UseDefaultCredential 
     [System.Xml.XmlNode]$webCollXmlNode=$service.GetListCollection()
     $listcol = $webCollXmlNode.List
     return $listcol        
}
 
Function GetListItems
{
      param([string]$site, [string]$listname)
      $uri=$site+"/_vti_bin/Lists.asmx?wsdl"
      $listsWebServiceReference = New-WebServiceProxy -Uri $uri -UseDefaultCredential 
      [System.Xml.XmlDocument]$xmlDoc=New-Object -TypeName System.Xml.XmlDocument
      [System.Xml.XmlElement]$query = $xmlDoc.CreateElement("Query")
      [System.Xml.XmlElement]$viewFields =$xmlDoc.CreateElement("ViewFields")
      [System.Xml.XmlElement]$queryOptions =$xmlDoc.CreateElement("QueryOptions")
      $viewFields.InnerXml = $viewFieldsValue
      $query.InnerXml = $queryValue
      $queryOptions.InnerXml = $queryOptionsValue
      [System.Xml.XmlNode]$nodeListItems =$listsWebServiceReference.GetListItems($listName, $viewName, $query, $viewFields, $rowLimit, $queryOptions, $null)
      $result = $nodeListItems.data.row
      return $result
}
 
#--------------------------------------- Work with the data ------------------------------------------
 
ac $logfile "Generating File Report for $($webURL) - $(Get-Date)"
 
#Get list of subsites
$allsubsites = GetAllSubWebCollection
 
$i = 1
$countfiles = 0
 
# Loop through each subsite and perform the following
foreach($site in $allsubsites)
{
    # Update progress bar
    Write-Progress -Activity "Generating report for sites.." -status "Processing $i sites of $($allsubsites.count)" -percentComplete ($i / $allsubsites.count*100)
 
    # Loop through each subsite and get collection of document libraries
    $alllistcol = GetListCollection($site.Url)
 
    # Perform the following for each document library
    foreach($list in $alllistcol)
    {
        if (($excludeLists -notcontains $list.Title) -and ($list.Basetype -eq "1"))
        {
            $files = GetListItems -site $site.Url -listname $list.Title
 
            # Loop through each file in the document library and perform the following
            foreach($file in $files)
            {
                Write-host "$($site.Title),$($list.Title),$($file.ows_LinkFileName)"
 
                # Use the following to add additional metadata columns
 
                $record = new-object System.Object
                $record | Add-Member -type NoteProperty -name Site -value $site.Title
                $record | Add-Member -type NoteProperty -name List -value $list.Title
                #$record | Add-Member -type NoteProperty -name FileTitle -value $file.ows_Title
                $record | Add-Member -type NoteProperty -name Filename -value $file.ows_LinkFileName
                $record | Add-Member -type NoteProperty -name Created -value $file.ows_Created
                $record | Add-Member -type NoteProperty -name CreatedBy -value $file.ows_Author
                $record | Add-Member -type NoteProperty -name Modified -value $file.ows_Modified
                $record | Add-Member -type NoteProperty -name ModifiedBy -value $file.ows_Editor
                $record | Add-Member -type NoteProperty -name ContentType -value $file.ows_ContentType
                if ($file.ows_File_x0020_Size)
                {
                    $record | Add-Member -type NoteProperty -name Filesize -value $file.ows_File_x0020_Size.split("([^#]+$)'")[-1]
                }
                $output += $record
                $countfiles++
 
                #$output += "$($site.Title),$($list.Title),$($file.ows_Title),$($file.ows_LinkFileName),$($file.ows_Created)"
            }
        }
    } 
    # Increment progress counter
    $i++
}
 
#-------------------------- Output to file ------------------------------
 
$output | export-csv $logfile -notype -force
write-host "Done - $(Get-Date) - found $($countfiles) files"
Comments ( 2 )

Microsoft SharePoint is not supported with version 4.0.30319.296 of the Microsoft .Net Runtime.

Problem

You try to configure SharePoint Diagnostic Studio for SharePoint 2010 and get the following error:

Microsoft SharePoint is not supported with version 4.0.30319.296 of the Microsoft .Net Runtime.

Solution

This occurs when you have Microsoft Windows Management Framework 3.0 (KB2506143) installed on your SharePoint server.

Note that if you installed this update, SharePoint 2010 Management Shell will also fail to work correctly unless you add the PowerShell.exe -version 2.0 parameter to your shortcut.

The best thing to do at this point is NOT to install Windows Management Framework 3.0

To uninstall it,

  • Go to Start -> Run -> appwiz.cpl
  • View Installed Updates
  • Under the group ‘Microsoft Windows’, locate the Microsoft Windows Management Framework 3.0 update
  • Uninstall

You will have to restart your server after uninstallation.

Re-run the SharePoint Diagnostic Studio configuration again and the error should no longer appear.

Comments ( 0 )