Shiv Rajawat
Shiv Rajawat

Reputation: 988

Sharepoint development using PowerShell

I'm trying to create sharepoint webparts using powershell. But each time I loads (Context.Load()) something, I'm getting errors.

Here is my code.

[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client").location))
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.runtime").location))

$tenantAdmin = "#####@ajoncloud.onmicrosoft.com"
$tenantAdminPassword = "#########"
$secureAdminPassword = $(convertto-securestring $tenantAdminPassword -asplaintext -force)
$siteURL = "https://ajoncloud.sharepoint.com/LND"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin,$secureAdminPassword) 
$ctx.Credentials = $credentials

This part is working completely fine. But if I try the following statements, I get errors.

$web = $ctx.Web
$ctx.Load($web)
$ctx.ExecuteQuery()

This is the error I'm getting.

Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."

Upvotes: 1

Views: 141

Answers (1)

Bernard Moeskops
Bernard Moeskops

Reputation: 1283

Your code is working fine when I try it myself. Maybe try the below piece of code and try to obtain a specific piece inside your SharePoint. Specify a certain list and try to obtain the fieldvalues. At first I got an error when running your code, but when I tried a different user and specified the below list it started working for both users.

[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client").location))
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.runtime").location))

$tenantAdmin = "your admin account"
$tenantAdminPassword = "your admin password"
$secureAdminPassword = $(ConvertTo-SecureString $tenantAdminPassword -AsPlainText -Force)
$siteURL = "your site/subsite"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
$ctx.credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin,$secureAdminPassword) 

$listTitle = "The name of your list" 
$list = $ctx.Web.Lists.GetByTitle($listTitle)
$fields = $list.Fields
$qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(10000,'ID','Created','Modified','Title')
$items = $list.GetItems($qry)
$ctx.Load($fields)
$ctx.Load($items)
$ctx.ExecuteQuery()

foreach($item in $items){
    $item.FieldValues.Title
}

Upvotes: 1

Related Questions