Posts tagged with "PowerShell"

Creating SharePoint alerts via CSOM

Posted within Administration Development on by Ryan Ball

I’m posting this as a useful reminder. It outlines how alerts can now be created via CSOM.

New SharePoint CSOM version released for SharePoint Online – February 2017

The included code sample is in C#, but I’ve translated it to PowerShell – which suits my administrative needs better.

[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.SharePoint.Client" ) | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.SharePoint.Client.Runtime" ) | Out-Null


# Set variables
$path = "C:\Temp\Usernames.txt"

$url = "https://xxxxxx.sharepoint.com/sites/help"

$list = "My List"

$title = "$list (Auto-subscribed)"


# Prompt the administrator to log in
$credential = Get-Credential -Credential $null


# Create a connection to SharePoint Online
$context = New-Object Microsoft.SharePoint.Client.ClientContext( $url )
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials( $credential.UserName, $credential.Password )


# Retrieve the targeted web
$web = $context.Web

$context.Load( $web )
$context.ExecuteQuery()


# Loop through the provided usernames and create a new alert for each one
$usernames = Get-Content -Path $path

foreach ( $username in $usernames )
{
    $user = $context.Web.EnsureUser( $username )

    $alert = New-Object Microsoft.SharePoint.Client.AlertCreationInformation
    $alert.List = $context.Web.Lists.GetByTitle( $list )
    $alert.AlertFrequency = [Microsoft.SharePoint.Client.AlertFrequency]::Daily
    $alert.AlertTime = ( Get-Date ).AddDays( 1 )
    $alert.AlertType = [Microsoft.SharePoint.Client.AlertType]::List
    $alert.AlwaysNotify = $false
    $alert.DeliveryChannels = [Microsoft.SharePoint.Client.AlertDeliveryChannel]::Email
    $alert.Status = [Microsoft.SharePoint.Client.AlertStatus]::On
    $alert.Title = $title
    $alert.User = $user
    $alert.EventType = [Microsoft.SharePoint.Client.AlertEventType]::All
    $alert.Filter = "1"

    $guid = $user.Alerts.Add( $alert )

    $user.Update()

    $context.ExecuteQuery()
}

Secure credentials within PowerShell

Posted within Administration on by Cornflower Design

For PowerShell scripts that need to access resources (e.g. a site within SharePoint) and be run as scheduled tasks, I will normally use an encrypted password…

Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString | Out-File "$PSScriptRoot\Password.txt"

… and then refer to it within my script.

$username = "me@domain.co.uk"
$password = Get-Content "$PSScriptRoot\Password.txt"

$securePassword = $password | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential( $username, $securePassword )

This <a href="https://blog.kloud.com.au/2016/04/21/using-saved-credentials-securely-in-powershell-scripts/">blog post by Kloud</a> covers some this technique in greater detail.

SharePoint Content Type IDs

Posted within Administration on by Cornflower Design

This is a handy PowerShell snippet for returning a list of all Content Types and their IDs within a SharePoint site.

$site = Get-SPSite http://www.domain.com
$web = $site.RootWeb
ForEach( $contentType in $web.ContentTypes ) { Write-Host $contentType.Name": "$contentType.ID }

Using PowerShell To Analyse The Contents Of A Folder

Posted within Administration on by Cornflower Design

# The path to interrogate
 $targetPath = "X:\Shared\FolderToBeInterrogated"
# The path to save the exported report
 $exportPath = "C:\Reports"
# Recursively get all files
 Get-ChildItem -Path $targetPath -Recurse -Force | Select Name, Extension, Length, CreationTime, LastWriteTime, LastAccessTime, FullName | Export-Csv -NoTypeInformation -Force "$exportPath\Report $( Get-Date -f yyyy-MM-dd ).csv"

Trouble Shooting SharePoint Errors

Posted within Administration on by Ryan Ball

For viewing in command prompt:

Get-SPLogEvent | ?{$_.Correlation -eq "<GUID>"} | SELECT Area, Category, Level, EventID, Message | Format-List

Export the results as text file:

Get-SPLogEvent | ?{$_.Correlation -eq "<GUID>"} | SELECT Area, Category, Level, EventID, Message | Format-List > C:\Error.log

Results can be retrieved faster if the time span is limited:

Get-SPLogEvent -StartTime YYYY-MM-DDTHH:mm:ss | ?{$_.Correlation -eq "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"} | SELECT Area, Category, Level, EventID, Message | Format-List

How Many Users In An Active Directory Group?

Posted within Development on by Cornflower Design

This is a useful PowerShell snippet for determining how many users there are in an Active Directory group.

(Get-ADGroup "CN=MyGroup,DC=domain,DC=co,DC=uk" -Properties *).Member.Count

Upload a .STP Template File

Posted within Administration on by Ryan Ball

This is a quick way to programmatically upload a .STP template file within SharePoint using PowerShell – useful if you’re transferring list templates from a development to a live environment.

$web = Get-SPWeb "http://mydomain"
$folder = $web.GetFolder( "List Template Gallery" )
$files = $folder.Files
$file = Get-ChildItem "C:\MyListTemplate.stp"
$newfile = $files.Add( "_catalogs/lt/MyListTemplate.stp", $file.OpenRead(), $true )
$web.Dispose()

Downloading Solutions from Central Administration

Posted within Administration on by Ryan Ball

This is a handy little PowerShell snippet that I needed to use today. There were two .WSP solutions installed within the SharePoint farm and I couldn’t locate the original source code.

$farm = Get-SPFarm
$solution = $farm.Solutions.Item("MySharePointSolution.wsp").SolutionFile
$solution.SaveAs("C:\MySharePointSolution.wsp")

PowerShell Snippets for Microsoft Exchange

Posted within Development on by Cornflower Design

These are two very handy PowerShell snippets that I use again and again within our work environment.

Retreive List of All Group Members

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
csvde -f C:\report.csv -s mydomain.co.uk -r "memberof=CN=Dept:MyTartgetGroup,OU=Domain Groups,DC=mydomain,DC=ac,DC=uk" -l "sAMAccountName,name, mail"

Retreive List of All Users with Permission to Email a Group

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Get-DistributionGroup "Dept:MyTargetGroup" | Select name,@{Name="AcceptMessagesOnlyFrom";Expression={[string]::join(";",($_.AcceptMessagesOnlyFrom | foreach {$_.Name}))}} | Export-Csv C:\report.csv

SharePoint & Item-Level Permissions within Document Libraries

Posted within Administration on by Ryan Ball

I have a love/hate relationship with SharePoint. Often the things that should be really simple, just aren’t. Take the “Item-level Permissions” option for instance. Every list appears to have this option (available via List Settings > Advanced Settings) except for document libraries. I’m sure the SharePoint Development Team at Microsoft have a very good reason for this…

Step forth PowerShell!

$web = Get-SPWeb http://mysharepointsite
$list = $web.Lists[“A Document Library”]
$list.ReadSecurity = 2
$list.WriteSecurity = 2
$list.Update()
$web.Dispose()

The ReadSecurity value can be one of the following:

1 = “Read all items”
2 = “Read items that were created by the user”

The “Create and Edit access” option can also be set by specifiying a value for WriteSecurity.

1 = “Create and edit all items”
2 = “Create items and edit items that were created by the user”
4 = “None”