Blog Image

PowerShell

SharePoint Powershell Commands

GoSharePoint Website
Documentation Blog

This blog is based on SharePoint 2013 PowerShell Commands. Please visit my other blog which contains SharePoint Documentation.

PnP PowerShell to Get List Items using CAML

Uncategorised Posted on Sun, September 06, 2020 18:25:10

#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#CAML Query to Filter List Items
$Query = “Completed”

#Get All List Items matching given query
$ListItems = Get-PnPListItem -List $ListName -Query $Query

#Loop through each Item
Write-host -f Green “Number of List Items Found:”$ListItems.Count
ForEach($ListItem in $ListItems)
{
Write-Host “Id :” $ListItem[“ID”]
Write-Host “Title :” $ListItem[“Title”]
}



Remove Ampisands from files

Administration Posted on Sat, September 05, 2020 21:43:07

$path = ‘c:\datasource’

$items = Get-ChildItem -Path $path -Filter ‘&.*’ -Recurse

foreach ($item in $items)
{
try
{
$item.Name
Rename-Item -Path $item.FullName -NewName $item.Name.Replace(‘&’,’_’)

    $output = "Amended '" +  $item.Name + "' to '" + $item.Name.Replace('&','_') + "'"
    Write-Host $output
}
catch
{
    $output = "Could not rename file '" +  $item.Name + "'"
    Write-Host $output
}

}

$items = Get-ChildItem -Path $path -Filter ‘~.‘ -Recurse

foreach ($item in $items)
{
try
{
$item.Name
Rename-Item -Path $item.FullName -NewName $item.Name.Replace(‘~’,’_’)

    $output = "Amended '" +  $item.Name + "' to '" + $item.Name.Replace('~','_') + "'"
    Write-Host $output
}
catch
{
    $output = "Could not rename file '" +  $item.Name + "'"
    Write-Host $output
}

}



Set External Sharing For Sites

Administration Posted on Sat, September 05, 2020 21:40:23

function SetExternalSharingForSites($csvrows, $adminUrl, $credentials, $logFile)
{
#Connect to Admin site and set sharing properties for all sites in CSV List
Connect-SPOService -Url $adminUrl -Credential $credentials;
foreach($row in $csvrows)
{
if ($row.RequestType -eq ‘Adhoc’ -or $row.RequestType -eq ‘Extranet’)
{

        try
        {
            if ($sitesWithErrors.Contains($row.Url) -eq $false)
            {
                WriteToLog -logFile $logFile -text ("Attempting to set External Sharing for " + $row.url) -ForegroundColor Yellow
                Set-SPOSite -Identity $row.url -SharingCapability ExistingExternalUserSharingOnly
                Set-SPOSite -Identity $row.Url -DisableSharingForNonOwners
                WriteToLog -logFile $logFile -text ("External Sharing enabled for " + $row.url) -ForegroundColor Green
            }
        }
        catch
        {
            WriteToLog -logFile $logFile -text ("Could not enable External Sharing for " + $row.url + '. ' + $Error[0].Exception.GetBaseException()) -ForegroundColor Red
            $sitesWithErrors.Add($row.Url,"Could not enable External Sharing");
        }
    }
}
Disconnect-SPOService

}



Connect To Tenant

Administration Posted on Sat, September 05, 2020 21:37:51

function ConnectToTenant($credentials)
{
# Connect to to Office 365
try{
Connect-SPOService -Url $global:adminUrl -Credential $credentials -ErrorAction Stop
write-host “Info: Connected succesfully to Office 365” -foregroundcolor green;
return $true;
}
catch{
write-host “Error: Could not connect to Office 365” -foregroundcolor red;
break;
}
}



Grant Site Collection Admin

Administration Posted on Sat, September 05, 2020 21:16:44

$adminUrl = ‘https://tenant-admin.sharepoint.com’;

if ($credentials -eq $null)
{
$credentials = Get-Credential
}

Connect-SPOService -Url $adminUrl -Credential $credentials -ErrorAction Stop

$siteUrl = ‘https:// tenant .sharepoint.com/sites/marketing

Set-SPOUser -Site $siteUrl -LoginName ‘username@domain.com’ -IsSiteCollectionAdmin $true



Create Word Automation Services

Service Applications Posted on Tue, June 28, 2016 07:17:00

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Creates the Word Automation Service

Check for existing service application and proxy

Check if application pool already exist, if not create it

====================================================================#>

#This service allows users to convert documents.

function Add-Module($strFileName){

Write-Host “Attempting to run ” $strFileName

<#====================================================================

Get SharePoint variables

====================================================================#>

Add-Module(“C:\Temp\SharePoint2013\GetVariables.ps1”)

If (Test-Path $strFileName){

&($strFileName)

}Else{

Write-Host “Cannot locate” $strFileName

}

}

#Allows to use SharePoint cmdlets from inside the Windows PowerShell command window

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null

#Get default SQL server

$DefaultDatabaseServer = (Get-SPDatabase | ? { $_.Type -eq “Configuration Database” }).NormalizedDataSource

#Get SQL server instance for the User Profile Application, Social,

$DatabaseServer = $WordServerInstance

$ServiceApplicationName = “Word Automation Services”

$ServiceName = “Word Automation Services”

$DatabaseName = “Word Automation Service”

$spAppPoolName = “Word Automation Services Application Pool”

$spAppPoolAcc = $WordAppPoolAcc

$MachinesToActivate = $WordMachinesToActivate.Split(“,”).trim()

Write-Host “”

Write-Host “========================================================”

Write-Host “SharePoint 2013 – Module ‘$ServiceApplicationName’…”

Write-Host “To SharePoint Servers” $MachinesToActivate

Write-Host “Application Pool Name -” $spAppPoolName

Write-Host “Application Pool Account – -” $spAppPoolAcc

Write-Host “Database Server Instance -” $DatabaseServer

Write-Host “Configuration DB -” $ConfigDB

Write-Host “========================================================”

Write-Host “”

Start-SPAssignment -Global | Out-Null

try

{

#Check for existing service application and proxy

$ExistingServiceApp = Get-SPServiceApplication | where-object {$_.Name -eq $ServiceApplicationName}

if ($ExistingServiceApp -eq $null)

{

Write-Host ” – Creating ‘$ServiceApplicationName'”

#Check if managed account already exist, if not exit

$spManagedAccount = Get-SPManagedAccount -Identity $spAppPoolAcc -ErrorAction SilentlyContinue

if ($spManagedAccount -eq $null)

{

Write-Host -f Red “- ” $ServiceName ” Managed Account – Unable to retrieve managed account” $spAppPoolAcc

exit -1

}

#Check if application pool already exist, if not create it

$ApplicationPool = Get-SPServiceApplicationPool -Identity $spAppPoolName -ErrorAction SilentlyContinue

if ($ApplicationPool -eq $null)

{

New-SPServiceApplicationPool -Name $spAppPoolName -Account $spManagedAccount | Out-Null

}

else

{

Set-SPServiceApplicationPool $ApplicationPool -Account $spManagedAccount | Out-Null

}

#Note: Proxy is automatically created

New-SPWordConversionServiceApplication -Name $ServiceApplicationName -ApplicationPool $spAppPoolName -DatabaseServer $DatabaseServer -DatabaseName $DatabaseName -Default | Out-Null

#Start service instances

Write-Host strTest “- Starting service instance”

foreach ($machine in $MachinesToActivate)

{

#Gets the service to determine its status

$service = $(Get-SPServiceInstance | where {$_.TypeName -match $ServiceName} | where {$_.Server -match “SPServer Name=”+$machine})

If ($service.Status -eq “Disabled”)

{

Write-Host -f Green “- Starting” $service.ID “on $machine”

Start-SPServiceInstance -Identity $service.ID | Out-Null

}

}

Write-Host “- Done creating ‘$ServiceApplicationName’.”

}else{

Write-Host -f Red ” – ServiceApplication ‘$ServiceApplicationName’ already exists.”

#Remove Application?

$RemoveApplication=read-host ‘Do you wish to remove Application? (Y/N)’

if ($RemoveApplication-eq”Y”)

{

write-host ” – Removing ‘$ServiceApplicationName’…”

Remove-SPServiceApplication $ExistingServiceApp -removedata -Confirm:$false

#Proxy is NOT automatically deleted

$ExistingServiceAppProxy = Get-SPServiceApplicationProxy | where-object {$_.Name -eq “$ServiceApplicationName Proxy”}

if ($ExistingServiceAppProxy -ne $null)

{

write-host “- Removing ‘$ServiceApplicationName proxy’…”

Remove-SPServiceApplicationProxy $ExistingServiceAppProxy -Confirm:$false

}

write-host “- Stopping service instance…”

Get-SPServiceInstance | where-object {$_.TypeName -eq $ServiceName} | Stop-SPServiceInstance -Confirm:$false | Out-Null

}

}

}

catch { write-Output $_ }

Stop-SPAssignment -Global | Out-Null



Create Visio Graphics Service

Service Applications Posted on Tue, June 28, 2016 07:16:28

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Creates the Visio Graphics Service

#This service allows users to share and view Visio web drawings using Visio Services.

#Read more: http://technet.microsoft.com/en-us/library/ee524059.aspx

====================================================================#>

#Allows to use SharePoint cmdlets from inside the Windows PowerShell command window

If ((Get-PsSnapin |?{$_.Name -eq “Microsoft.SharePoint.PowerShell”})-eq $null)

{

Add-PsSnapin Microsoft.SharePoint.PowerShell | Out-Null

}

<#====================================================================

Get SharePoint variables

====================================================================#>

Add-Module(“C:\Temp\SharePoint2013\GetVariables.ps1”)

function Add-Module($strFileName){

Write-Host “Attempting to run ” $strFileName

If (Test-Path $strFileName){

&($strFileName)

}Else{

Write-Host “Cannot locate” $strFileName

}

}

$strInstallationFilesPath = (Split-Path ($PSCommandPath))

$ServiceApplicationName = “Visio Graphics Service”

$ServiceName = “Visio Graphics Service”

$spAppPoolName = “Visio Graphics Service Application Pool”

$spAppPoolAcc = $VisioAppPoolAcc

$CustomFilePath= $strInstallationFilesPath + “\Visio Graphics Service\”

$MachinesToActivate = $VisioMachinesToActivate.Split(“,”).trim()

#Get default SQL server

$DefaultDatabaseServer = (Get-SPDatabase | ? { $_.Type -eq “Configuration Database” }).NormalizedDataSource

#Get SQL server instance for the User Profile Application, Social,

$DatabaseServer = $VisioServerInstance

Write-Host “”

Write-Host “========================================================”

Write-Host “SharePoint 2013 – Module ‘$ServiceApplicationName’…”

Write-Host “To SharePoint Servers” $MachinesToActivate

Write-Host “Application Pool Name -” $spAppPoolName

Write-Host “Application Pool Account – -” $spAppPoolAcc

Write-Host “Database Server Instance” $DatabaseServer

Write-Host “Configuration DB” $ConfigDB

Write-Host “========================================================”

Write-Host “”

Write-Host “SharePoint 2013 – ‘$ServiceApplicationName’…”

Start-SPAssignment -Global | Out-Null

try

{

#Check for existing service application and proxy

$ExistingServiceApp = Get-SPServiceApplication | where-object {$_.Name -eq $ServiceApplicationName}

if ($ExistingServiceApp -eq $null)

{

Write-Host ” – Creating ‘$ServiceApplicationName'”

#Check if managed account already exist, if not exit

$spManagedAccount = Get-SPManagedAccount -Identity $spAppPoolAcc -ErrorAction SilentlyContinue

if ($spManagedAccount -eq $null)

{

Write-Host -f Red $strTest “- ” $ServiceName ” Managed Account – Unable to retrieve managed account” $spAppPoolAcc

exit -1

}

#Check if application pool already exist, if not create it

$ApplicationPool = Get-SPServiceApplicationPool -Identity $spAppPoolName -ErrorAction SilentlyContinue

if ($ApplicationPool -eq $null)

{

New-SPServiceApplicationPool -Name $spAppPoolName -Account $spManagedAccount | Out-Null

}

else

{

Set-SPServiceApplicationPool $ApplicationPool -Account $spManagedAccount | Out-Null

}

New-SPVisioServiceApplication -Name $ServiceApplicationName -ApplicationPool $spAppPoolName | Out-Null

#Create Service Application Proxy

Write-Host ” – Creating ‘$ServiceApplicationName’ proxy”

New-SPVisioServiceApplicationProxy -Name “$ServiceApplicationName Proxy” -ServiceApplication $ServiceApplicationName | Out-Null

Add-Module($CustomFilePath + “Manage the Visio Graphics Service – Global Settings.ps1”)

#Start service instances

Write-Host ” – Starting service instance”

foreach ($machine in $MachinesToActivate)

{

#Gets the service to determine its status

$service = $(Get-SPServiceInstance | where {$_.TypeName -match $ServiceName} | where {$_.Server -match “SPServer Name=”+$machine})

If ($service.Status -eq “Disabled”)

{

Write-Host ” – Starting” $service.ID “on $machine”

Start-SPServiceInstance -Identity $service.ID | Out-Null

}

}

Write-Host ” – Done creating ‘$ServiceApplicationName’.`n”

}else{

Write-Host -f Red $strTest” – ServiceApplication ‘$ServiceApplicationName’ already exists.”

#Remove Application?

$RemoveApplication=read-host ‘Do you wish to remove Application? (Y/N)’

if ($RemoveApplication-eq”Y”)

{

write-host ” – Removing ‘$ServiceApplicationName’…”

Remove-SPServiceApplication $ExistingServiceApp -removedata -Confirm:$false

#Proxy is NOT automatically deleted

$ExistingServiceAppProxy = Get-SPServiceApplicationProxy | where-object {$_.Name -eq “$ServiceApplicationName Proxy”}

if ($ExistingServiceAppProxy -ne $null)

{

write-host ” – Removing ‘$ServiceApplicationName proxy’…”

Remove-SPServiceApplicationProxy $ExistingServiceAppProxy -Confirm:$false

}

write-host ” – Stopping service instance…”

Get-SPServiceInstance | where-object {$_.TypeName -eq $ServiceName} | Stop-SPServiceInstance -Confirm:$false | Out-Null

}

}

}

catch { write-Output $_ }

Stop-SPAssignment -Global | Out-Null



Create Work Management Service Application

Service Applications Posted on Tue, June 28, 2016 07:14:31

<#====================================================================

Copyright © 2015, September. Michael Pomfret

Creates the Work Management Service Application which provides task aggregation across work management systems, including Microsoft SharePoint Products, Microsoft Exchange Server, and Microsoft Project Server.

Check for existing service application and proxy

Check if application pool already exist, if not create it

Creates Service Application Proxy

====================================================================#>

#Allows to use SharePoint cmdlets from inside the Windows PowerShell command window

If ((Get-PsSnapin |?{$_.Name -eq “Microsoft.SharePoint.PowerShell”})-eq $null)

{

Add-PsSnapin Microsoft.SharePoint.PowerShell | Out-Null

}

<#====================================================================

Get SharePoint variables

====================================================================#>

Add-Module(“C:\Temp\SharePoint2013\GetVariables.ps1”)

function Add-Module($strFileName){

Write-Host “Attempting to run ” $strFileName

If (Test-Path $strFileName){

&($strFileName)

}Else{

Write-Host “Cannot locate” $strFileName

}

}

#Get default SQL server

$DefaultDatabaseServer = (Get-SPDatabase | ? { $_.Type -eq “Configuration Database” }).NormalizedDataSource

#Get SQL server instance for the User Profile Application, Social,

$DatabaseServer = $WorkServerInstance

$ServiceApplicationName = “Work Management Service Application”

$ServiceName = “Work Management Service”

$spAppPoolAcc = $AppPoolAcc

$spAppPoolName = “Work Management Service Application Pool”

$MachinesToActivate = $WorkMachinesToActivate.Split(“,”).trim()

Write-Host “”

Write-Host “========================================================”

Write-Host “SharePoint 2013 – Module ‘$ServiceApplicationName’…”

Write-Host “To SharePoint Servers” $MachinesToActivate

Write-Host “Application Pool Name -” $spAppPoolName

Write-Host “Application Pool Account – -” $spAppPoolAcc

Write-Host “Database Server Instance -” $DatabaseServer

Write-Host “Configuration DB -” $ConfigDB

Write-Host “========================================================”

Write-Host “”

Start-SPAssignment -Global | Out-Null

try

{

#Check for existing service application and proxy

$ExistingServiceApp = Get-SPServiceApplication | where-object {$_.Name -eq $ServiceApplicationName}

if ($ExistingServiceApp -eq $null)

{

Write-Host ” – Creating ‘$ServiceApplicationName'”

#Check if managed account already exist, if not exit

$spManagedAccount = Get-SPManagedAccount -Identity $spAppPoolAcc -ErrorAction SilentlyContinue

if ($spManagedAccount -eq $null)

{

Write-Host -f Red “- ” $ServiceName ” Managed Account – Unable to retrieve managed account” $spAppPoolAcc

exit -1

}

#Check if application pool already exist, if not create it

$ApplicationPool = Get-SPServiceApplicationPool -Identity $spAppPoolName -ErrorAction SilentlyContinue

if ($ApplicationPool -eq $null)

{

Write-Host “- Creating $spAppPoolName using managed account to $spManagedAccount”

New-SPServiceApplicationPool -Name $spAppPoolName -Account $spManagedAccount | Out-Null

}

else

{

Write-Host ” – Updating $ServiceApplicationName managed account to $spManagedAccount”

Set-SPServiceApplicationPool $ApplicationPool -Account $spManagedAccount | Out-Null

}

New-SPWorkManagementServiceApplication -Name $ServiceApplicationName -ApplicationPool $spAppPoolName | Out-Null

#Create Service Application Proxy

Write-Host ” – Creating ‘$ServiceApplicationName’ proxy”

New-SPWorkManagementServiceApplicationProxy -Name “$ServiceApplicationName Proxy” -DefaultProxyGroup -ServiceApplication $ServiceApplicationName | Out-Null

#Start service instances

Write-Host “- Starting service instance”

foreach ($machine in $MachinesToActivate)

{

#Gets the service to determine its status

$service = $(Get-SPServiceInstance | where {$_.TypeName -match $ServiceName} | where {$_.Server -match “SPServer Name=”+$machine})

If ($service.Status -eq “Disabled”)

{

Write-Host ” – Starting” $service.ID “on $machine”

If(-eq”Live”)

{

Start-SPServiceInstance -Identity $service.ID | Out-Null

}

}else{

Write-Host -f Green “- “$service.ID “on $machine already started”

}

}

Write-Host “- Completed creating ‘$ServiceApplicationName’.”

}else{

Write-Host -f Red ” – ServiceApplication ‘$ServiceApplicationName’ already exists.”

#Remove Application?

$RemoveApplication=read-host ‘Do you wish to remove Application? (Y/N)’

if ($RemoveApplication-eq”Y”)

{

write-host “- Removing ‘$ServiceApplicationName’…”

Remove-SPServiceApplication $ExistingServiceApp -removedata -Confirm:$false

#Proxy is NOT automatically deleted

$ExistingServiceAppProxy = Get-SPServiceApplicationProxy | where-object {$_.Name -eq “$ServiceApplicationName Proxy”}

if ($ExistingServiceAppProxy -ne $null)

{

write-host “- Removing ‘$ServiceApplicationName proxy’…”

Remove-SPServiceApplicationProxy $ExistingServiceAppProxy -Confirm:$false

}

write-host “- Stopping service instance…”

Get-SPServiceInstance | where-object {$_.TypeName -eq $ServiceName} | Stop-SPServiceInstance -Confirm:$false | Out-Null

}

}

}

catch { write-Output $_ }

Stop-SPAssignment -Global | Out-Null



Next »