0

Clone user permissions on SharePoint Online – Office 365

I had a request from one my clients to clone the permissions of one user to another for a SharePoint Online site.

I had created a simple PowerShell script that automates this process. It is a very common scenario when someone leaves the organization and somebody else takes that role or you want a backup for an employee and wants the same permissions to the backup person as well

It’s a simple task and I hope the following script comes in handy for you, Happy Scripting! You can also download the script from SPO_CloneUserPermissions.ps1


<#
.SYNOPSIS
Close user permissions of user to another in SharePoint Online

.AUTHOR
Susheel Dakoju

.DATE
04/21/2017

.DESCRIPTION
1. Fetch all the groups that the user is part of
2. Add ActualUser to the same groups

.Note
- This script requires admin privileges on the machine that is being executed on!
-
#>

#SharePoint online Admin site URL
$SPOAdmiURL = "https://yoursite-admin.sharepoint.com/"
$username = "username@onmicrosoft.com"
$password = "@@@@@@@@"

#Url of the SharePoint Online Site
$SPOSiteURL = 'https://yoursite.sharepoint.com/sites/test'

#User used as reference
$ReferenceUser = 'sdakoju@onmicrosoft.com'
#The actual user that needs to be added to Groups
$ActualUser = 'rkevin@onmicrosoft.com'

#Create a credential object
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)

#Connect to SharePoint Online using the credentials
Connect-SPOService -Url $SPOAdmiURL -Credential $cred

#Get the SharePoint Online Site Object
$site = Get-SPOSite $SPOSiteURL

#Get the user object of the reference user
$user = Get-SPOUser -Site $site -LoginName $ReferenceUser

#Loop through Groups and add the actual user
$user.Groups | Foreach-Object {

#Fetch Group Object that the reference user is part of
$group = Get-SPOSiteGroup -Site $site -Group $_

#Add 'ActualUser' to the same group that the reference user is part of
Add-SPOUser -Site $SPOSiteURL -LoginName $ActualUser -Group $group.LoginName

}

Note:

– It is assumed that you have SharePoint Online module installed on the machine you are running this script. If you do not have, please follow this link to download SharePoint Online Management Shell

– I had the following errors while running the script, I am jotting them here as they may be helpful for you.

Error 1:

  • Identity Client Runtime Library (IDCRL) could not look up the realm information for a federated sign-in. Or
  • The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios. Or
  • The ‘username’ argument is invalid. Or
  • The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios.

Solution:

  • I was using a wrong username. Please make sure you have right admin username and password for the SharePoint Online site that you are running against.

Error 2:

  • The site https://yoursite.sharepoint.com/sites/test/ is not properly formed

Solution:

  • There is a trailing slash at the end of the URL it should be ‘https://yoursite.sharepoint.com/sites/test’ and NOT ‘https://yoursite.sharepoint.com/sites/test/’
0

Powershell Create IIS Site

<#
.SYNOPSIS
 Create and IIS Site

.DESCRIPTION
 - This script creates and IIS based on the user input
 - The  script takes back up of the existing IIS configuration
   Restores back to the the backed up IIS Configuration if something goes wrong
 - This script is meant for education/demonstration purpose only and not meant for production use
 - This script plays by the user inputs, you could take the inputs as aruguments. For instance,
   #$siteName    = Read-Host 'What is the name of your site' 
       could be
   #$siteName    = $args&#91;0&#93;
   You could invoke the script as InstallIISSite.ps1 &#91;WebsiteName&#93; &#91;AppPoolName&#93; &#91;Port&#93; &#91;Path&#93; (&#91;domain\user&#93; &#91;password&#93;)

.Note
 - This scripts requires admin priviliges!
#>

# Add 'WebAdministration' modules to the current session. 
# The modules must be installed on the local computer or a remote computer

Import-Module WebAdministration

#Suspends the activity in a script or session for the specified period of time in secods
Start-Sleep 2 
 
# Get the user inputs for SiteName, AppPool, Port, Path for the site, user and password
$siteName    = Read-Host 'What is the name of your site?'           
$appPoolName = Read-Host 'What is the name of the application pool?'
$port        = Read-Host 'Specify the port number'
$path        = Read-Host 'Choose the path for your website'
$user        = Read-Host 'Specify user in the followng fashion domain\username'
$password    = Read-Host 'Enter password' -AsSecureString 

<# Or you can have the following

$siteName    = $args&#91;0&#93;           
$appPoolName = $args&#91;1&#93;
$port        = $args&#91;2&#93;
$path        = $args&#91;3&#93;
$user        = $args&#91;4&#93;
$password    = $args&#91;5&#93;

You may invoke the script as 
InstallIISSite.ps1 &#91;WebsiteName&#93; &#91;AppPoolName&#93; &#91;Port&#93; &#91;Path&#93; (&#91;domain\user&#93; &#91;password&#93;)
#>
 
#Backup the IIS Configuration
#Create the name for back up folder
$backupName = "$(Get-date -format "yyyyMMdd-HHmmss")-$siteName"

#"Backing up IIS config to backup named $backupName"
# Backup will be created at C:\Windows\System32\inetsrv\backup
$backup = Backup-WebConfiguration $backupName

 
try { 
    # Delete the website & app pool if already existed
    if (Test-Path "IIS:\Sites\$siteName") {
        "Removing existing website $siteName"
        Remove-Website -Name $siteName -Confirm
    }
 
    if (Test-Path "IIS:\AppPools\$appPoolName") {
        "Removing existing AppPool $appPoolName"
        Remove-WebAppPool -Name $appPoolName -Confirm
    }
 
    #Remove sites using the same port
    foreach($site in Get-ChildItem IIS:\Sites) {
        if( $site.Bindings.Collection.bindingInformation -eq ("*:" + $port + ":")){
            "Warning: Found an existing site '$($site.Name)' already using port $port. Removing it..."
             Remove-Website -Name  $site.Name -Confirm
             "Website $($site.Name) removed"
        }
    }
 
    "Create an appPool named $appPoolName with v4.0 framework"
    $pool = New-WebAppPool $appPoolName
    $pool.managedRuntimeVersion = "v4.0"
    if ($user -ne $null -AND $password -ne $null) {
	"Setting Application Pool to run under the $user"
		$pool.processmodel.identityType = 3
		$pool.processmodel.username = [string] $user
		$pool.processmodel.password = [string] $password
	}
    else
    {
    #If no user name is not specified, set the ID as NetworkService
      $pool.processModel.identityType = 2
    }
	
    $pool | Set-Item

    if ((Get-WebAppPoolState -Name $appPoolName).Value -ne "Started") {
        throw "Application pool $appPoolName was created but did not start!"
    }
 
    "Create a website $siteName pointing at $path and create with port $port"
    $website = New-Website -Name $siteName -PhysicalPath $path -ApplicationPool $appPoolName -Port $port
 
    if ((Get-WebsiteState -Name $siteName).Value -ne "Started") {
        throw "Website $siteName was created but did not start!"
    }
 
    "Website and Application Pool was created and started successfully"
} 
catch
 {
    "Oops something went wrong! Rolling back web server to its initial state. Please wait..."
     Start-Sleep 3 
     Restore-WebConfiguration $backupName
     "IIS Restore complete."
     throw
}
0

Introduction to PowerShell Basics


<#
.SNOPSYS
Excute Basic Powershell commands for absoulute beginners

.DESCRIPTION
This script is meant for education/demonstration purpose only
and not meant for production use

- This whole script is self explanatory
- The aim of this script is is introduce few basic of powershell which
would help to kick start using powershell

.NOTES
Author: Susheel Dakoju
Date Authored: 04/14/2015
#>
#--------------------------------------------------------------------------------
# Example 1: Windows PowerShell cmdlets similar to the .NET framework. See below
# Execute the following and see for yourself
# Most of the commandlet are in the form of Verb-Noun fashion
# 'Let' as told by Dictionary.com a diminutive suffix attached to nouns (booklet, piglet, ringlet, anklet, wristlet).
#--------------------------------------------------------------------------------
Get-Date
(Get-Date).GetType()
#--------------------------------------------------------------------------------
#Examplet 2: Similar to how you would do in .NET. ToShortDateString()can change the output format.
#The idea behind is example is show how simliar the experience would be for a .NET developer
#--------------------------------------------------------------------------------
(Get-Date).ToShortDateString().GetType()

#------------------------!IMPORTANT-----------------------------------------------
# Example 3: PIPELINES
# This is one of the most important concepts where one command can create object and pass on to the next command let
# This is not new and has been part for scripting for years.
# Another imprtant thing to notice is the Format-table option which lets you format your output.
#--------------------------------------------------------------------------------
Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 4 -Property CPU,VirtualMemorySize | Format-Table
#------------------------!IMPORTANT-----------------------------------------------
# Example 4: Alias
# Powershell ships with is own aliases this is for a good reason.
# For instance cls will work, but at the back ground it execure Clear-Host cmdlet
# You can create your Alias; Remembers Aliases are valid only per Session they
# get purged once session close use Import-Alias and Export-Alias commandlets
#--------------------------------------------------------------------------------
Get-Alias -Name dir # = Get-ChildItem
New-Alias ListItMyWay get-childitem

#--------------------------------------------------------------------------------
# Example 5: Variables and DataTypes
# Execute the following and check for yourself
#--------------------------------------------------------------------------------
$StoreMyInteger = 4
$StoreMyInteger.GetType()

$StoreMyString = "PowerShell Rocks!"
$StoreMyString.GetType()

Comparison and logical operators

#--------------------------------------------------------------------------------
# Example 6: Variables and DataTypes
# Execute the following and check for yourself
<#
#--------------------------------------------
a. Comparision Operators
#--------------------------------------------
-eq Equal
-ne Not equal
-ge Greater than or equal
-gt Greater than
-lt Less than
-le Less than or equal
-like Wildcard comparison
-notlike Wildcard comparison
-match Regular expression comparison
-notmatch Regular expression comparison
-replace Replace operator
-contains Containment operator
-notcontains Containment operator
-ceq Case-sensitive Equals
-creplace Case-sensitive replace
#--------------------------------------------
b. Types
#--------------------------------------------
-is Is of a type
-isnot Is not of a type
-as As a type, no error if conversion fails

#--------------------------------------------
c. Logical operators
#--------------------------------------------
-and Logical And
-or Logical Or
-not logical not
! logical not

#--------------------------------------------
d. Bitwise operators
#--------------------------------------------
-band Bitwise and
-bor Bitwise or

#--------------------------------------------
e. Format Operator
#--------------------------------------------
"format_string" -f Object1, Object2,...
#>
#>
#-----------
# Working with 'is' Operator: Re
#-----------
$stringValue = "PowerShell"
$stringValue -is "String"
# Just for fun know the retun Type
$($stringValue -is "String").GetType()

#-----------
# Working with 'eq' and 'ceq': Equal and Case-Sensitive Equal Operator
#-----------
$smallCase = "abc"
$UpperCase = "aBc"
$smallCase -ceq $UpperCase #return False
$smallCase -ceq $UpperCase #return True

#-----------
# Working with 'Like'
#-----------
"susheel" -like "sus*" #return true

#-----------
# Working with 'Replace'
#-----------
"Windows Command Prompt" -replace "Command Prompt","Power Shell"

#end of Example 6: Variables and DataTypes

#--------------------------------------------------------------------------------
# Example 7: Arrays
# These are similar to .NET Array. See ways to declare and use them
# The interesting part is to assign items of different types similar to C# Object Type
#--------------------------------------------------------------------------------
$array1 = @('1','2', (Get-Alias -Name cls))
#--------------------------------------------------------------------------------
# Example 8: Script Flow and Execution Control
# Only gave example for if, else. Try the others by yourself
# Conditional Execution: 1. if elseif else | 2. Switch | 3. Switch -option
# Iteration Statements: 1. For | 2. For Each | 3. While | 4. do while
#--------------------------------------------------------------------------------

if ($status) {
$output = "time Service is enabled"
} Else {
$output = "time service disabled"
}
Write-Output $output

#--------------------------------------------------------------------------------
# Example 9: Functions
# A very basic function to add numbers and how to execute it.
#--------------------------------------------------------------------------------

Function AddNumbers([int] $value1, [int] $value2)
{
return ($value1 + $value2)
}

AddNumbers 1 2

#----------------------***! Very Important !***----------------------------------
# Example 10: Execution Policy
# A very basic function to add numbers and how to execute it.
<#
a. Restricted: No script execution is allowed.

B. RemoteSigned: Script execution is allowed only for the scripts authored
on the local computer but not for any scripts from the external sources

Not be executed unless they are signed by a trusted publisher.

C. AllSigned: All the scripts must be signed by a trusted publisher including
scripts authored on the local computer

D. Unrestriced: All scripts ARE executed without any restriction.
#>
#--------------------------------------------------------------------------------
#----------------------
# Fetch the current Execution Policy
#----------------------
Get-ExecutionPolicy

#----------------------
# Set Execution Policy
#----------------------
Set-ExecutionPolicy -ExecutionPolicy Restricted

&nbsp;

0

Introduction to PowerShell for Azure – Creating a VM

<pre>&lt;#
.SNOPSYS
Excute Basic Azure command and create a VM

.DESCRIPTION
This script is meant for education/demonstration purpose only
and not meant for production use
- Initial section of the script covers basics commands to get connected with Azure
- The rest of the script covers creating a VM with SQL Server running.

.NOTES
Author: Susheel Dakoju
Date Authored: 04/13/2015
#&gt;
#-----------------------------------------------------------------------------
# 1. Connect to Azure: Option 1: Add-AzureAccount
#-----------------------------------------------------------------------------
#Connect
Add-AzureAccount
#Check subscription details
Get-AzureSubscription
#-----------------------------------------------------------------------------
# 1. Connect to Azure: Option 2: Get-AzurePublishSettingsFiles
#-----------------------------------------------------------------------------
#Download PublishSettingsFile
Get-AzurePublishSettingsFile
#Import Setting Files
Import-AzurePublishSettingsFile "C:PowershellAzureVisual Studio Ultimate with MSDN-4-14-2015-credentials.publishsettings"

#-----------------------------------------------------------------------------
# 2. Export all the exiting images in the VM Gallery and
# copy the name image you want to create
# Note: There are more elegant way of doing this.Here the most basic form is demonstration. See below
&lt;#
$vmimages | where {$_.Label -like 'sql server 2014*'} | select Label, RecommendedVMSize, PublishedDate | Format-Table -AutoSize
$imgtouse = $vmimages | where {$_.Label -eq 'SQL Server 2014 RTM Enterprise on Windows Server 2012 R2' `
-and $_.PublishedDate -eq '6/9/2014 3:00:00 AM'} | select ImageName
#&gt;
#-----------------------------------------------------------------------------
Get-AzureVMImage &gt; C:PowershellAzureimages.txt

#-----------------------------------------------------------------------------
# 3. Create new Azure VM
#-----------------------------------------------------------------------------
New-AzureVMConfig -Name 'sdcapsandbox1' -InstanceSize Basic_A3 -ImageName 'fb83b3509582419d99629ce476bcb5c8__SQL-Server-2014-RTM-12.0.2361.0-Enterprise-ENU-Win2012R2-cy14su05' |`
Add-AzureProvisioningConfig -Windows -AdminUsername 'sdcapsandboxuser1' -Password 'Administrator@1234'|`
New-AzureVM -Location 'East US' -ServiceName 'sdcapsandbox1'
#-----------------------------------------------------------------------------
# 3.Check if the New VM is generated
#-----------------------------------------------------------------------------
#Get-AzureVM

#------------------------------------------------------------------------------------
# Optional: If New-AzureVM errors out on storage account. Keep the following handy
# - Use one of the storage accounts or create a new one run Set-AzureSubscription
#------------------------------------------------------------------------------------
#Get-AzureStorageAccount
#Set-AzureSubscription -SubscriptionId 16c41f83-c83e-476a-8fdc-51b8ae69849f -CurrentStorageAccount mystorageaccount
</pre>
0

Introduction to PowerShell for SharePoint Online -2


<#
.SYNOPSIS
Create SharePoint Sites on SharePoint Online

.DESCRIPTION
- This script demonstrated creating sites for SharePoint Online.

--------------------------------------------------------------------------------
Code generated by: Susheel Dakoju., Windows Powershell Host v 3.0
Generated on: 04-12-2015 19:28
Generated by:
Organization:
--------------------------------------------------------------------------------
#>

#SharePoint Online Information
$SharePointOnlineURL = "https://contoso.sharepoint.com/"
$SharePontOnlineAdminSiteURL = "https://contoso-admin.sharepoint.com/"
$AdminUser = "usename@contoso.onmicrosoft.com"

#New Site Information
$newSiteURL = "testsite3"
$newSiteTitle = "testsite3"
$newsiteTemplate = "STS#0"

#--------------------------------------------------------------------
#1. Create SharePoint Online Site
#--------------------------------------------------------------------

#--------------------
# Connect to SharePoint Online Service
#--------------------
Connect-SPOService -Url $SharePontOnlineAdminSiteURL -credential $AdminUser

#Prepare Credentails
$password = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SharePointOnlineURL)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminUser, $password)
$ctx.Credentials = $credentials

#Create Web
$webCreationInformation = New-Object Microsoft.SharePoint.Client.WebCreationInformation
$webCreationInformation.Url = $newSiteURL
$webCreationInformation.Title = $newSiteTitle
$webCreationInformation.WebTemplate = $newsiteTemplate
$newWeb = $ctx.Web.Webs.Add($webCreationInformation)

#Load and Execute
$ctx.Load($newWeb)
$ctx.ExecuteQuery()

Write-Host "Title" $newWeb.Title

#End of Create SharePoint Online Site

0

Introduction to Powershell for SharePoint Online -1


<#
.SYNOPSIS
#Basic command lets for SharePoint online

.DESCRIPTION
# This powershell script is generated just to get
very basic understanding
# of how you can connect with SharePoint Online and
execute basic GET Commands
# The scripts generates output in two formats CSV and
HTML to two folder on the system

.NOTES
#Author: Susheel Dakoju.
#Generated on: 04-12-2015 19:28
#Generated by:
#Organization: Windows Powershell Host v 3.0

#>

#Import-Module Microsoft.Online.Sharepoint.PowerShell

<#
1.Connect-SPOService
Description: Shows how a SharePoint Online global administrator with a user name and password connects to a SharePoint Online Administration Center that
has the URL http://contoso-admin.sharepoint.com/.
#>

$URL = "https://contoso.sharepoint.com/"
$AdminURL = "https://contoso-admin.sharepoint.com/"
$AdminUser = "usernam@contoso.onmicrosoft.com"
$csvurlprefix = "C:PowershellOutputcsv"
$htmlurlprefix = "C:PowershellOutputhtml"

Connect-SPOService -Url $AdminURL -credential $AdminUser
#-----------------------------------------------------------------------------------------------#
<#
2.Get-SPOSite
Description: Lists the site collection with detailed properties.
#>

# Export to CSV
Get-SPOSite $URL -Detailed | select * | Export-CSV -path "$($csvurlprefix)GetSPOsite_CSV.csv"

# Export to HTML
Get-SPOSite $URL -Detailed | select * | ConvertTo-Html | Set-Content "$($htmlurlprefix)GetSPOsite_HTML.html"

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

<#
3. Get-SPOTenant
Description: Returns the organization-level site collection properties such as
StorageQuota, StorageQuotaAllocated, ResourceQuota,ResourceQuotaAllocated, and SiteCreationMode.
#>
# Export to CSV
Get-SPOTenant | Export-CSV -path "$($csvurlprefix)GetSPOTenat_CSV.csv"

# Export to HTML
Get-SPOTenant | ConvertTo-Html | Set-Content "$($htmlurlprefix)GetSPOTenant_HTML.html"

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

<# 4. Get-SPOUser

Description: Returns one user or security group account inside group Team Site Members from the site collection #>

# Export to CSV
Get-SPOUser -Site $URL | Export-CSV -path "$($csvurlprefix)GetSPOUser_CSV.csv"

# Export to HTML
Get-SPOUser -Site $URL| ConvertTo-Html | Set-Content "$($htmlurlprefix)GetSPOUser_HTML.html"
<# 5. Get-SPOSiteGroup #>

#Gets all the groups on the specified site collection.

# Export to CSV
Get-SPOSiteGroup -Site $URL | Export-CSV -path "$($csvurlprefix)SPOSiteGroup_CSV.csv"

# Export to HTML
Get-SPOSiteGroup -Site $URL | ConvertTo-Html | Set-Content "$($htmlurlprefix)SPOSiteGroup_HTML.html"

0

Introduction to PowerShell for SharePoint 2013 -2 (Administration)


&amp;lt;#
.SYNOPSIS
--------------------------------------------------------------------------------
Code generated by: Susheel Dakoju., Windows Powershell Host v 3.0
Generated on: 04-11-2015 19:28
Generated by:
Organization:
--------------------------------------------------------------------------------
.DESCRIPTION
- This script is generated for Capital Area .NET SharePoint Special Interest Group Meetup demonstration of basic Powershell commands for SharePoint
- This script is running against SharePoint 2013 powered by Powershell version 3.0
- Run as administrator to run the script sucessfully.
- This script is not for production use. The commenting and Intending is done to suite for quick demonstration and may not be adopted for organizational use
--------------------------------------------------------------------------------
#&amp;gt;
#---------------------------------------------------------------------#
#1. Create a new SiteCollection
#Prequsites/Assumption: A ready made webapplication with no root sitecollection created via GUI or Powershell
#---------------------------------------------------------------------#
New-SPSite -OwnerAlias SDsdakoju -Url http://contoso.com:4234/ -Name "CAPAREA SharePoint Demo 1" -Template STS#1

#---------------------------------------------------------------------#
#2. Create multiple new SiteCollection
#Prequsites/Assumption: A ready made webapplication along with root site sitecollection created via GUI or Powershell
#---------------------------------------------------------------------#
#-----------------------
#Create a new managed path
#-----------------------
New-SPManagedPath –RelativeURL "demo1" -WebApplication "http://contoso.com:4234/"
#-----------------------
#Create a new multiple sites
#-----------------------
New-SPSite -OwnerAlias SDsdakoju -Url http://contoso.com:4234/demo1/test -Name "CAPAREA SharePoint Demo 1" -Template STS#1 #already created
New-SPSite -OwnerAlias SDsdakoju -Url http://contoso.com:4234/demo1/test1 -Name "CAPAREA SharePoint Demo 1" -Template STS#1 #already created
New-SPSite -OwnerAlias SDsdakoju -Url http://contoso.com:4234/demo1/test2 -Name "CAPAREA SharePoint Demo 1" -Template STS#1 #already created
New-SPSite -OwnerAlias SDsdakoju -Url http://contoso.com:4234/demo1/test3 -Name "CAPAREA SharePoint Demo 1" -Template STS#0 #already created

#---------------------------------------------------------------------#
#3.Remove/Delete SiteCollection
#---------------------------------------------------------------------#
Remove-SPSite -Identity http://contoso.com:4234/demo1/test2 -Confirm

#Check if deleted
Get-SPSite -WebApplication http://contoso.com:4234/
#---------------------------------------------------------------------#
#3.Export a site
#All the operation in this section can be done even with UI under Back up and Restore section in CA
#---------------------------------------------------------------------#
Export-SPWeb -Identity http://contoso.com:4234/demo1/test3 -Path demo1_test3.cmp

#---------------------------------------------------------------------#
#4.Import a site
#All the operation in this section can be done even with UI under Back up and Restore section in CA
#---------------------------------------------------------------------#
Import-SPWeb -Identity http://contoso.com:1234/ -Path demo1_test3.cmp -Confirm -Force
#---------------------------------------------------------------------#
#5.Export a List or Library
# This is similar to Exporting a whole SPWEB but if Item URL is specified it exports only that.
#---------------------------------------------------------------------#
Export-SPWeb -Identity http://contoso.com:4234/demo1/test3/ -Path demo1_test3_doc1.cmp -ItemUrl "/demo1/test3/Shared Documents"

#---------------------------------------------------------------------#
#6.Import a List or Library
# This is similar to Importing a whole SPWEB, since Item URL is specified in export, import will get list only.
#---------------------------------------------------------------------#
Import-SPWeb -Identity http://contoso.com:1234/capareademo1/ -Path demo1_test3_doc1.cmp -Confirm -Force

0

Introduction to PowerShell for SharePoint 2013 -1 (Developer)


<#
.SYNOPSIS
--------------------------------------------------------------------------------
Code generated by: Susheel Dakoju., Windows Powershell Host v 3.0
Generated on: 04-11-2015 19:28
Generated by:
Organization:
--------------------------------------------------------------------------------
.DESCRIPTION
- This script is generated for Capital Area .NET SharePoint Special Interest Group Meetup demonstration of basic Powershell commands for SharePoint
- This script is running against SharePoint 2013 powered by Powershell version 3.0
- Run as administrator to run the script sucessfully.
- This script is not for production use. The commenting and Intending is done to suite for quick demonstration and may not be adopted for organizational use
--------------------------------------------------------------------------------
#>

#---------------------------------------------------------------------------------------#
# Getting Started
#---------------------------------------------------------------------------------------#

#---------------------------------------------------------------------#
#1. Get Current Powershell Version
#---------------------------------------------------------------------#
$PSVersionTable.PSVersion

#---------------------------------------------------------------------#
#2. Get count of Commands with 'SP' in the name SharePoint Snap-In
#---------------------------------------------------------------------#
Get-Help *sp* | Measure-Object

#---------------------------------------------------------------------#
#3. Get count of Commands with 'SP' in the name BEFORE ADDING SharePoint Snap-In
#---------------------------------------------------------------------#
Add-PSSnapin -Name Microsoft.SharePoint.Powershell
Get-Help *sp* | Measure-Object

#---------------------------------------------------------------------#
#4. Get count of Cmdlets with 'sp' in the name AFTER ADDING SharePoint Snap-In
#---------------------------------------------------------------------#
Get-Command *sp* | Where {$_.CommandType -match "cmdlet" }| Measure-Object
Get-Help *sp* | Measure-Object

#---------------------------------------------------------------------#
#5. Get count of Applications with 'sp' in the name AFTER ADDING SharePoint Snap-In
#---------------------------------------------------------------------#
Get-Command *sp* | Where {$_.CommandType -match "Application" }| Measure-Object
Get-Help *sp* | Measure-Object

#---------------------------------------------------------------------#
#6. Get count of Applications with 'sp' in the name AFTER ADDING SharePoint Snap-In
#---------------------------------------------------------------------#
Get-Command *sp* | Where {$_.CommandType -Match "cmdlet" -and $_.ModuleName -Match "Microsoft.SharePoint.PowerShell" }| Measure-Object
Get-Help *sp* | Measure-Object

#---------------------------------------------------------------------------------------#
# Developer: The folloowing script block creats and add content to SharePoint 2013 Sites
#---------------------------------------------------------------------------------------#
#---------------------------------------------------------------------#
#1. Get all available Web Templates
#---------------------------------------------------------------------#
Get-SPWebTemplate

#---------------------------------------------------------------------#
#2. Get availablet Web Templates which are team site or black site
#---------------------------------------------------------------------#
Get-SPWebTemplate | Where {$_.Title -match "Team Site" -or $_.Title -match "Blank Site"}

#---------------------------------------------------------------------#
#3. Demo: Insert Command from Show-Command window
#---------------------------------------------------------------------#
Show-Command
#New-SPWeb -Url http://conteso.com:1234/capareademo1/Caparea_1 -AddToTopNav -Name Caparea_1 -Template STS#1 -UseParentTopNav
#New-SPWeb -Url http://conteso.com:1234/capareademo1/Caparea_2 -AddToTopNav -Name Caparea_2 -Template STS#1 -UseParentTopNav

#----------------------**** Important *****---------------------------#
#4. The Start-SPAssignment cmdlet properly disposes of objects used with variable assignments
# 'Global' Parameter- All objects are assigned to the lifetime of the script
# Read more at : https://technet.microsoft.com/en-us/library/ff607664.aspx
#---------------------------------------------------------------------#
Start-SPAssignment -Global

#---------------------------------------------------------------------#
#5. Create two SharePoint List of Type Tasks and Document Library.
#---------------------------------------------------------------------#
$web = Get-SPWeb -Identity http://conteso:1234/capareademo1/Caparea_1
$web.Lists.Add("Project Tasks", "Holds Project Tasks","Tasks")
$web.Lists.Add("Project Documents", "Holds Project Documents","DocumentLibrary")

#---------------------------------------------------------------------#
#6. Updating SharePoint Content
#---------------------------------------------------------------------#
$lst = $web.Lists["Project Tasks"]
$lst.Title = "Project Tasks 1"
$lst.Update()
#forget update

#---------------------------------------------------------------------#
#7. Remove SharePoint Content
#---------------------------------------------------------------------#
Remove-SPWeb -Identity http://conteso.com:1234/capareademo1/Caparea_1 -Confirm
Remove-SPWeb -Identity http://conteso.com:1234/capareademo1/Caparea_2 -Confirm

#-------------------------**** Important *****------------------------#
#4. The Stop-SPAssignment cmdlet properly disposes of objects used with variable assignments
# 'Global' Parameter- Disposed of when the Stop-SPAssignment cmdlet is called
# Read more at : https://technet.microsoft.com/en-us/library/ff607664.aspx
#---------------------------------------------------------------------#
Stop-SPAssignment -Global

0

Windows Command Prompt vs Windows PowerShell

With PowerShell gaining more popularity and more adoption among developers/administrators, there is also increasing confusion between Command Prompt and PowerShell.

I will try my best to show case the differences between these two based on my experience.

Please read my other blogs on PowerShell to get some basic understanding of what it is and how it can change your life as  an IT pro.

Lets gets started….

What is a shell?

Shell is a program that takes commands from the keyboard or mouse and passes on to operating system to perform requested actions. This could be as simple as opening a text file, navigating through your C or D drive, opening your internet explorer etc.

For instance look at the following examples and see why they qualify as Shell.

1. Windows Explorer ( is a shell ):  It is one of the most commonly used shell with a GUI (Graphical User Interface).
This qualifies to be a Shell because, all it does is it takes input for your keyboard or mouse and helps you navigate through your files and folders.

2. Command prompt ( is a shell ):
 DOES NOT have a GUI works only with predefined commands like dir, mkdir, taskkill etc. which takes only text as input.

3. Windows PowerShell (is a shell)DOES NOT have a GUI works with predefined command-lets like Get-Process, Get-Help etc which takes objects as input and not just text.

Difference 1: Commands (PowerShell can execute all the commands that Command Prompt and beyond.)

Following images shows how ‘dir’ commands works on both Command Prompt and PowerShell. Do you see any difference? Not much, correct?

Powershell and Command Prompt Difference

Powershell and Command executing ‘Dir’ Command

Please see below image executing a command-let ‘Get-ChildItem’ to list the same files with in the same Images folder. If you observe the previous example, ‘PowerShell’ was running ‘Dir’ command but behind the scenes it is executing ‘Get-ChildItem’ command-let. PowerShell ships with Command-lets only, some these command-lets execute on behalf of the DOS commands.

PowerShell Showing Get-ChildItem

PowerShell executing Get-ChildItem

 

The following table contains a selection of the cmdlets that ship with PowerShell, noting similar commands in other well-known command-line interpreters. Many of these similar commands come out-of-the-box defined as aliases within PowerShell, making it easy for people familiar with other common shells to start working.[1]

Comparision of PoweShell cmdlets with similar commands

Comparision of PoweShell cmdlets with similar commands


If you would like to know the total count of all  the available command-lets available try to run the following command – @(Get-Command).Count.
The count varies from version to version of the Powershell, the following is for version 3.

PowerShell Showing Command Count

PowerShell Showing Command Count

Check your version by running $PSVersionTable.PSVersion command.

Difference 2: Generation Gap (Automation and Security)

Command prompt was born in early 1980s,  it was doing well during its infancy and childhood , but when it reached its adult hood around 2005, it was facing some harsh challenges: Automation and Security.

Automation: 

It is very hard to find instances where you do not require to automate. All the things that you do on a daily basis can be automated such as creating an IIS site, clean up logs, back up databases and the list goes on…

Let see the following scenario where automation helps tremendously.

Imagine that your website is hosting ‘The Super Bowl’ or ‘The American Idol’ finale, can you fathom the amount of traffic you can expect for these events? Also think about the very next day or as a matter of fact, the very next hour once these events are done? There is very high probability or almost guaranteed that you will drop to 5% of your traffic that you had while these events are streaming live.

Do you believe it makes sense to purchase hundreds of servers just for a day or few hours and not use them for the rest of the year? How about any other events that can draw huge audiences but not as much as Super Bowl? You will be under utilizing your hardware then.

So ideally you need to scale-out or scale-down when ever appropriate. This scenario can be applied even for a day, for instance, if your’s is a stock brokerage firm and is very typical that you might have heavy traffic from 9:00 to 4:00 pm only, so does it mean that you can shut down few of your servers after 4:00 pm? Absolutely!!

It would be close to  impossible to achieve something at this scale and time with out automation. Command prompt cannot achieve this with the limited commands it has and as a matter of fact it wasn’t designed or built for these use cases. One the flip side, Powershell is designed and well baked for automation.

Security:

Security is a broad topic and I am not going to deep dive, but this section will help you get some sense of what kind of security challenges that PowerShell solves.

Bad guys running .bat or .ps1 files:

For example, if you are running a .bat file (batch file: series of commands) it is all or nothing proposition, for instance, if a bad guy somehow gets access to your server, he can execute all the batch files he wished for.

With PowerShell you can set execution policy to run only digitally signed scripts, to go even further, you can even restrict the server not to run the PowerShell at all.

Impersonation or running in a different security context:

It is very easy to impersonate user with PowerShell it has built in cmd-lets to support it. It is possible with CMD prompt as well but not very straight forward.

Remote Command Execution:

Typically if you have to run batch files, you need to have these running on the server. With PowerShell it is designed to execute command remotely with out even copying the PowerShell script to the server that it is supposed to run. How this works? PowerShell is built on .NET and uses cmd-lets to accomplish tasks. As long as the server has the cmd-lets on the server, you should be able to run any command from any where. You can accomplish the same with Command Prompt, of-course not as elegant solution as with PowerShell.

Restricted permissions on the server itself:

When using Command prompt your options are limited. Even common administrative tasks might be tough or not even feasible to accomplish, for instance, modifying Registry and other administrative functions. With PowerShell ships with cmd-lets that make these administrative tasks absolutely pain free.

Difference 3: Adoption and Support

PowerShell is part of the CEC (Common Engineering Criteria) since 2009, which means that all the products shipped since then have to support PowerShell. All Microsoft products must ship with cmd-lets that help with administrative and maintenance tasks. Microsoft Exchange team is one of the early adopters and the product can be completely administered via PowerShell.

All such products from Microsoft stack, ship with these cmd-lets going forward. It is very unlikely that the will be any changes or improvements with command prompt to support these products. Even all the third party tools that are build on Mircosoft tools and software will provide support for PowerShell and not Command Prompt.

References:

[1] https://en.wikipedia.org/wiki/Windows_PowerShell

Disclaimer:

All data and information provided on this blog is for informational purposes only makes no representations as to accuracy, completeness, recentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.