Quantcast
Channel: SharePoint Pals - PowerShell
Viewing all 31 articles
Browse latest View live

How To Get Inventory report Of Web parts added to SharePoint site page In SharePoint 2013

$
0
0

While planning for the Migration or other purpose sometimes, we need to know the web parts added to the SharePoint Pages, This inventory is not available on any of the existing migration tools handy. The below script will give a clear output of the WebpartName, PageURL, Title, URL, CreatedBy, WebpartID, WebpartType, ModifiedBy and Library or PageName

 $ver = $host | select version if($Ver.version.major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"} if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0)) { Add-PSSnapin Microsoft.SharePoint.PowerShell } cls try{ 	#Specify a directory for which to log the results 	$0 = $MyInvocation.MyCommand.Definition 	$dp0 = [System.IO.Path]::GetDirectoryName($0)  	$LoggingDirectory = $dp0 	$logFile=$("$dp0\Logs\WebParts_Site_SitePagesLayout_LogInformation.txt") 	$ExecutionStartTime = (Get-Date -UFormat "%Y-%m-%d_%I:%M:%S %p").tostring() 	Write "Script started at" $ExecutionStartTime >> $logFile 	Write-Host "Script started at" $ExecutionStartTime 	$PageLayout_Webparts_DetailsCSV =@() 	#Create a variable based on the current date and time 	$StartTime = (Get-Date -UFormat "%Y-%m-%d_%I-%M-%S %p").tostring()  	#Dynamically generate the log file name 	$Filename = "$LoggingDirectory\Result\WebPartDetails_In_SitePages_Pages_Library_" +$StartTime +".csv"      	$webapplist = Get-SPWebApplication 	foreach($webappUrl in $webapplist){ 		try{ 			#Specify the Web Application to be targeted 			$WebApplicationURL = $webappUrl.Url      			Write "`r`n web application URL" $WebApplicationURL "is being investigated" >> $logFile 						 			#Get all sites within each of the specified web application 			$AllSites = Get-SPSite -WebApplication $WebApplicationURL -Limit All      			 			foreach($Site in $AllSites){ 				Write "`r`nInside Site'" + $Site.Url  >> $logFile 	    		try{ 					#Return all webs in each site collection returned to the AllWebs variable 				    $AllWebs = $Site.Allwebs 				     				    #Perform some actions against each web retrieved from the current target site collection 				    foreach($Web in $AllWebs){ 					try{ 							$SitePageLib = $Web.GetFolder("SitePages")                              							foreach($file in $SitePageLib.Files){      								if($file){                                     if($file.Name.Contains(".aspx")){                                  									    $manager = $web.GetLimitedWebPartManager($file.Url,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)                                                									    $webCollection = $manager.WebParts             							            if($webCollection.Count -ne 0)             							            {             							             							                for($i =0;$i -lt $webCollection.Count; $i++)             							                {             							                    write ($i + 1).ToString()  " "  $webCollection[$i].GetType().Name  " "  $webCollection[$i].Title ',Web URL:' $Web.Url ',File URL:' $file.Url >> $logFile	 									 											    $PageLayout_Webparts_DetailsCSV+=New-Object PSObject -Property @{ 											    URL=$Web.Url; 											    Title=$Web.Title; 											    PageURL=$file.Url;	                                                 PageTitle=$file.Title;                                                 LibraryName='Site Pages';								                                                 WebpartID=$webCollection[$i].ID;                                               											    WebpartName=$webCollection[$i].Title; 											    WebpartType=$webCollection[$i].GetType().Name;                                                 CreatedBy=$file.Author.DisplayName;                                                 ModifiedBy=$file.ModifiedBy.DisplayName}							 							                }             							              							            }                                         if($manager){$manager.Dispose()} 								    }                                 } 							} 					 							$PagesLib = $Web.GetFolder("Pages")                             foreach($Item in $PagesLib.Files){                                 if($Item){                                     if($Item.Name.Contains(".aspx")){                                  									    $manager = $web.GetLimitedWebPartManager($Item.Url,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)                                                									    $webCollection = $manager.WebParts             							            if($webCollection.Count -ne 0)             							            {             							             							                for($i =0;$i -lt $webCollection.Count; $i++)             							                {             							                    write ($i + 1).ToString()  " "  $webCollection[$i].GetType().Name  " "  $webCollection[$i].Title ',Web URL:' $Web.Url ',File URL:' $Item.Url >> $logFile	 									 											    $PageLayout_Webparts_DetailsCSV+=New-Object PSObject -Property @{ 											    URL=$Web.Url; 											    Title=$Web.Title; 											    PageURL=$Item.Url;	                                                 PageTitle=$Item.Title;								                                                 LibraryName='Pages';                                                   WebpartID=$webCollection[$i].ID;                                               											    WebpartName=$webCollection[$i].Title; 											    WebpartType=$webCollection[$i].GetType().Name;                                                 CreatedBy=$Item.Author.DisplayName;                                                 ModifiedBy=$Item.ModifiedBy.DisplayName}							 							                }             							              							            }                                         if($manager){$manager.Dispose()} 								    }                                 }                             }                               $Web.Dispose() 						} 						catch [Exception]{ 							Write $_.Exception|format-list -force >>$logFile 							Write-Host -f red $_.Exception|format-list -force 						} 						finally{ 							if($Web){ 								$Web.Dispose() 							} 						} 					} 					$Site.Dispose() 				} 				catch [Exception]{ 					Write $_.Exception|format-list -force >>$logFile 					Write-Host -f red $_.Exception|format-list -force 				} 				finally{ 					if($Site){ 						$Site.Dispose() 					} 				} 			}  		}  		catch [Exception]{ 			Write $_.Exception|format-list -force >>$logFile 			Write-Host -f red $_.Exception|format-list -force 		}  	} 	$PageLayout_Webparts_DetailsCSV | Export-CSV -path $Filename -notype  } catch [Exception]{ 	Write $_.Exception|format-list -force >>$logFile 	Write-Host -f red $_.Exception|format-list -force } $EndTime = (Get-Date -UFormat "%Y-%m-%d_%I:%M:%S %p").tostring() Write "Script stopped at" $EndTime >> $logFile Write-Host "Script stopped at" $EndTime 



Result

clip_image002

Hope the handy script helps to get the inventory and save few hours of effort.

Happy Coding,

Hariramakrishnan Vasuthevan


ExecuteQuery” with “0” argument(s): “The remote server returned an error: (403) Forbidden–On SharePoint PowerShell CSOM

$
0
0

The above said exception looks very strange. Because, I have installed the SP Online Management Shell and all the DLLs were properly installed. But, when I try to execute the below code, on the ExecuteQuery, I am getting an exception of 403 forbidden.

 $UserName="sathish@*******.onmicrosoft.com"  $Password = ConvertTo-SecureString  "********" -AsPlainText -Force  $URL="https://*******.sharepoint.com/sites/DeveloperSite"  $SiteListName="SiteRequests"  $SPCredentials = New-Object -typename System.Management.Automation.PSCredential -argumentlist $UserName,$Password  Connect-PnPOnline -Url $URL -Credentials $SPCredentials               $SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)     $context = New-Object Microsoft.SharePoint.Client.ClientContext($URL)     $context.Credentials = $SPOCredentials       $web = $context.web      $context.load($web)     $context.ExecuteQuery()         Disconnect-PnPOnline 

After few investigations found that, there is a conflict between the DLLs in the loading order. The only thing on the above code is, I am using SPO Online commands (SPO) for few reason and the context.executequery (CSOM) as well. That’s were the issue starts.

Then by loading the Microsoft.SharePoint.Client.dll and the Microsoft.SharePoint.Client.Runtime.dll explicitly, the exception gone. The complete code is as follows.

 $UserName="sathish@*******.onmicrosoft.com"  $Password = ConvertTo-SecureString  "********" -AsPlainText -Force  $URL="https://*******.sharepoint.com/sites/DeveloperSite"  $SiteListName="SiteRequests"  $SPCredentials = New-Object -typename System.Management.Automation.PSCredential -argumentlist $UserName,$Password  Connect-PnPOnline -Url $URL -Credentials $SPCredentials          Import-Module "C:\SATHISH\\Archive\ClientDLLs.O365\Microsoft.SharePoint.Client.dll"     Import-Module "C:\SATHISH\\Archive\ClientDLLs.O365\Microsoft.SharePoint.Client.Runtime.dll"       $SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)     $context = New-Object Microsoft.SharePoint.Client.ClientContext($URL)     $context.Credentials = $SPOCredentials       $web = $context.web      $context.load($web)     $context.ExecuteQuery()         Disconnect-PnPOnline 

Hope this will help while implementing both SPO and CSOM on the same PowerShell Script.

Happy Coding,

Sathish Nadarajan.

How to connect to SharePoint Online using PnP PowerShell and SharePoint Online Management Shell

$
0
0

Hello,

Here we are going to connect SharePoint Online using PnP PowerShell and SharePoint Online Management Shell from your machine. If you have an issue while accessing PnP from your Windows 7 or 8 please refer this article – How to use PnP PowerShell in Windows 7 or Windows 8 machine

Here we are have two different approach to connect SharePoint Online site using PowerShell.

1. PnP PowerShell (useful for provisioning of site, adding content type, columns, lists etc)

2. SharePoint Online Management Shell (useful for handling functionality in admin side like services, delete site etc)

Connecting to SharePoint Online using PnP PowerShell:

Open the PowerShell as an Administrator and run the below command, because we need to have PowerShell Gallery in your machine.

Install-Module -Name SharePointPnPPowerShellOnline

clip_image002

Once the PowerShell Gallery is installed, you can connect to your SharePoint online site and check whether can access SharePoint online site from your system.

Connect-PnPOnline -Url https://yoursite.sharepoint.com/sites/mysite

clip_image004

You will get a prompt and it asks for the credentials (If you don’t want this prompt then you can add your site, username and password in “Credential Manager” (Start -> Credential Manager) and click on “Add Generic Credential“.

Now you will be connected to this site as far as this PowerShell window is alive and if you want to disconnect then you use the command. You can check by running

Get-PnPList and you will receive all the lists available in the site

clip_image006

Disconnect-PnPOnline

There are various PnP command commands available in Microsoft site and you can utilize those as per your need. We can use this main for Provisioning of site with predefined template. In the below link you can find PnP commands.

https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/add-pnpapp?view=sharepoint-ps

Connecting to SharePoint Online using SharePoint Online Management Shell:

Here we need to install a package called SharePoint Online Management Shell and it is available in the below link, and this is useful when you want to do something in Admin level where you would like to connect to service, delete site etc.

https://www.microsoft.com/en-us/download/details.aspx?id=35588

clip_image008

Install the downloaded Windows Installer in your machine. Open the Windows PowerShell and enter the below script to connect to SharePoint Online service, the URL should needs to be admin SharePoint URL

Connect-SPOService -Url https://yoursite-admin.sharepoint.com/

clip_image010

Now you will be connected to this site as far as this PowerShell window is alive and if you want to disconnect then you use the command. You can check by running.

clip_image012

Happy Coding

Ahamed

How to use PnP PowerShell in Windows 7 or Windows 8 machine

$
0
0

Hi,

If you are not using windows 10 and still you want to use PnP PowerShell then you are at the right place. Follow the below steps and install whatever is necessary to make your PnP PowerShell work in your Windows 7 or 8 system.

Here I am using Windows 7 and I opened my Window PowerShell as an administrator.

If you want to keep track on everything you do on your PowerShell then run the below script

clip_image002

We need to update PowerShell version to 5.0 or latest (to check your existing version then type $PSVersionTable and hit enter)

clip_image003

Step 1: Check your Execution Policy by running Get-ExecutionPolicy and if it is not RemoteSigned, then run the below script to set it as RemoteSigned

Set-ExecutionPolicy RemoteSigned

clip_image005

Step 2: Download Windows Management Framework 5.1 from Microsoft site, the link is given below

https://www.microsoft.com/en-us/download/details.aspx?id=54616 and choose you download according based on your OS

clip_image007

clip_image009

Step 3: Once the file is downloaded, install the .msu file (Close all existing PowerShell window). Reboot the system after installation is completed.

clip_image011

After system reboot, open you PowerShell and check for the version ($PSVersionTable) you can notice it as v5.1

clip_image013

Now you are good to go for PnP PowerShell commands in your Windows 7 or 8 OS.

Happy Coding

Ahamed

How to enable site classification in modern SharePoint site

$
0
0

The site classification option is not enabled by default in modern site, and you need to configure it using either CSOM or PowerShell script.

Site classification is basically used to define the sensitivity of the data. So, you can use the below script is used to enable the site classification on the tenant level


 Write-Output -msg "Start : Module loading Process" $modulePath = "C:\Program Files\SharePoint Online Management Shell\SharePointPnPPowerShellOnline"         Add-Type -Path ($modulePath + "\SharePointPnP.PowerShell.Online.Commands.dll")         Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.dll")         Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.Runtime.dll")         Add-Type -Path ($modulePath + "\Microsoft.Online.SharePoint.Client.Tenant.dll") Write-Output -msg "End : Module loading Process" $UserName="test@123.onmicrosoft.com" $pwd ="********" $siteURL="https://<<tenant>>.sharepoint.com" $Credentials = New-Object Microsoft.SharePoint. Client.SharePointOnlineCredentials($UserName, (ConvertTo-SecureString $pwd -AsPlainText -Force)) $encpassword = convertto-securestring -String $pwd -AsPlainText -Force $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $encpassword Connect-PnPOnline -Url $siteURL -Credentials $cred Write-Output $siteURL Connect-PnPOnline -Scopes "Directory.ReadWrite.All" Enable-PnPSiteClassification -Classifications "HBI","LBI","Top Secret" -UsageGuidelinesUrl $siteURL -DefaultClassification "HBI" 


After you have enabled this site classification, you see an additional field How sensitive is your data while creating modern team or communication site.

Thanks!

How to Delete the Modern Sites Using PowerShell in SharePoint Office 365

$
0
0


In this article, a small PowerShell Snippet to delete the SiteCollections from Office 365 is explained.

There are two methods used in this script. Which is mandatory. Because, when we delete from the UI or only delete the site, the site will remain in the Recycle Bin. We need to clear the site from the Recycle bin as well. Otherwise, when we try to create again with the same site name, system will thrown an exception.


 # Delete the SiteCollection  ##================================================================================================ ## Description	: To Delete the Sitecollections     ## Author		: Sathish ## Date			: 05-Apr-2018 ##================================================================================================  # ============================================ Setup Input Paths =================================  cls    $Host.UI.RawUI.WindowTitle = "-- Delete the Site Collection --"  $StartDate = Get-Date   Write-Host -ForegroundColor White "------------------------------------" Write-Host -ForegroundColor White "| Delete the Site Collection |" Write-Host -ForegroundColor White "| Started on: $StartDate |" Write-Host -ForegroundColor White "------------------------------------"     ################# Set the Current Path as Execution Path ####################  $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent Set-Location $scriptBase  ############# set the Error Preference ################  $ErrorActionPreference = "Stop"   $adminUrl = Read-Host "Enter the Admin URL of your Tenant"  #connect to the Tenant Admin Site Connect-SPOService -Url $adminUrl  try {     #Delete the Site     $siteURL = Read-Host "Enter the URL of the site to be deleted"       #Delete the Site from the Tenant     Remove-SPOSite -Identity $siteURL -Confirm:$false       #Delete the Site from the Recycle Bin      Remove-SPODeletedSite -Identity $siteURL -Confirm:$false       Write-Host -ForegroundColor Green $siteURL "Site Deleted Successfully"  } catch {     cls     Write-Host -ForegroundColor Red "Exception Occurred"      Write-Host -ForegroundColor Red $Error[0].Exception.Message } 

Happy Coding,

Sathish Nadarajan.

PowerShell script to change the People web part properties on a modern SharePoint site

$
0
0

In this article, let us see how to change the site contact properties on a People web part for the multiple site since we can’t go and change it manually every time if we need to update the properties for the multiple site collection. To avoid this manual activity, we can use PowerShell script

The below script is used to get the site owner information from the excel file and retrieve the web part present on the site’s home page and update the propertyJSON for the people web part with the values provided in the excel file.


 Write-Output -msg "Start : Module loading Process" $modulePath = "C:\Program Files\SharePoint Online Management Shell\SharePointPnPPowerShellOnline"         import-module ($modulePath + "\SharePointPnPPowerShellOnline.psd1")         Add-Type -Path ($modulePath + "\SharePointPnP.PowerShell.Online.Commands.dll")         Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.dll")         Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.Runtime.dll")         Add-Type -Path ($modulePath + "\Microsoft.Online.SharePoint.Client.Tenant.dll") Write-Output -msg "End : Module loading Process" $inputFilePath="D:\XXX\Input.xlsx" $UserName="test@xxx.onmicrosoft.com" $pwd ="xxxxxxx" try { #Get the input sites from Excel File $objExcel = New-Object -ComObject Excel.Application $objExcel.Visible = $false $objExcel.UserControl= $True [threading.thread]::CurrentThread.CurrentCulture = 'en-US' $WorkBook = $objExcel.Workbooks.Open($inputFilePath) $WorkSheet = $WorkBook.sheets.item("Sheet1") $rowMax = ($WorkSheet.UsedRange.Rows).count for ($i=2; $i -le $rowMax; $i++) {        $createdSiteURL=$worksheet.Rows.Item($i).Columns.Item(1).Text     $primaryOwner=$worksheet.Rows.Item($i).Columns.Item(2).Text     $secondaryOwner=$worksheet.Rows.Item($i).Columns.Item(3).Text      $encpassword = convertto-securestring -String $pwd -AsPlainText -Force     $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $encpassword # Connect Site     Connect-PnPOnline -Url $createdSiteURL -Credentials $cred     Write-Output $createdSiteURL #Get the Webparts available in the home page and update the propertiesjson for People Webpart     $webpart=Get-PnPClientSideComponent -Page Home      foreach($w in $webpart)     {       if($w.Title -eq "People")       {         $peoplewbInstanceId=$w.InstanceId         $peopleName="[{`"id`":`"i:0#.f|membership|"+$primaryOwner+"`"},{`"id`":`"i:0#.f|membership|"+$secondaryOwner+"`"}]"         $jsonp='{"title":"Site Contact","layout":1,"persons":'+$peopleName+'}'         Set-PnPClientSideWebPart -Page "Home" -Identity $peoplewbInstanceId -PropertiesJson $jsonp         Set-PnPClientSidePage -Identity "Home" -Publish       }        }     } } catch {      Write-Output $_.Exception.Message } $objExcel.quit() 


Hope this helps!

PowerShell script to set user email in the access request settings on Modern SharePoint Site

$
0
0


In this article, let us see how to change or add the user to access request list

The access request feature allows people to request access to content that they do not currently have permission to see. As a site owner, you can configure the feature to send you mail when someone requests access to a site. You can then choose whether to approve or decline their request. If you approve the request, you can also specify the specific level of permission you’d like to assign to a user.

 #Load SharePoint CSOM Assemblies  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  #Set Variables for Site URL  $SiteURL= "https://xxx.sharepoint.com/sites/xxx/"  $AccessReqEmail="xxx@xxx.onmicrosoft.com"  #Setup Credentials to connect  $Cred = Get-Credential  $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)  Try {  #Setup the context  $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  $Ctx.Credentials = $Cred  #Get the current settings  $Web = $Ctx.Web  $Ctx.Load($web.AllProperties)  $web.RequestAccessEmail  $Ctx.ExecuteQuery()  #Set Access request Email  $Web.RequestAccessEmail =$AccessReqEmail  #Member settings  $Web.MembersCanShare = $True  $web.AssociatedMemberGroup.AllowMembersEditMembership = $False  $web.AssociatedMemberGroup.Update()  $Web.Update()  $Ctx.ExecuteQuery()  Write-Host "Access Request Settings applied"  }  Catch {  } 

Hope this helps!

Thanks


PowerShell script to create bulk sub sites in modern site and associate group to that site

$
0
0


In this article, let us see how to create bulk sites by accessing csv in modern site and associate default group to that site.

 Clear-host  Write-Output -msg "Start : Module loading Process" $modulePath = "C:\Program Files (x86)\SharePointPnPPowerShellOnline\Modules\SharePointPnPPowerShellOnline" import-module ($modulePath + "\SharePointPnPPowerShellOnline.psd1") Add-Type -Path ($modulePath + "\SharePointPnP.PowerShell.Online.Commands.dll") Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.dll") Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.Runtime.dll") Add-Type -Path ($modulePath + "\Microsoft.Online.SharePoint.Client.Tenant.dll") Write-Output -msg "End : Module loading Process"  $cred = Get-Credential $csv = import-csv -Path "D:\Scripts\SiteInput.csv" Clear-Content "D:\SiteCreationLog.txt" try { foreach($value in $csv) { $ParentURL=$value.ParentSiteURL $TargetURL=$value.URL $WebTemplate=$value.Template $Title=$value.Title $Description=$value.Description $URL= $TargetURL -replace $ParentURL+'/'  if($WebTemplate -eq "Team") {       #Connect to Site Collection            Connect-PnPOnline -Url $ParentURL -Credentials $cred     #Create sub web with unique permissions     New-PnPWeb -Title $Title -Url $URL -Description $Description -BreakInheritance -InheritNavigation -Template "STS#3"     Disconnect-PnPOnline     Connect-PnPOnline -Url $TargetURL -Credentials $cred     $owner = (Get-PnPContext).Credentials.UserName      #Create default groups for the new web     $OwnerGroupName=$URL+" Owners"     $MemberGroupName=$URL+" Members"     $VisitorGroupName=$URL+" Visitors"      $ownerGroup = New-PnPGroup -Title $OwnerGroupName -Owner $owner      Set-PnPGroup -Identity $ownerGroup -SetAssociatedGroup Owners     Set-PnPGroupPermissions -Identity $ownerGroup -AddRole "Full Control"            $memberGroup = New-PnPGroup -Title $MemberGroupName -Owner $owner     Set-PnPGroup -Identity $memberGroup -SetAssociatedGroup Members     Set-PnPGroupPermissions -Identity $memberGroup -AddRole "Edit"      $visitorGroup = New-PnPGroup -Title $VisitorGroupName -Owner $owner     Set-PnPGroup -Identity $visitorGroup –SetAssociatedGroup Visitors
     Set-PnPGroupPermissions -Identity $visitorGroup -AddRole "Read"          $TargetURL+" PASS" | Out-File -FilePath D:\SiteCreationLog.txt -Append } else {     Write-Error "Invalid Template Name"      $TargetURL+" Invalid Template Name"| Out-File -FilePath D:\SiteCreationLog.txt -Append } } } catch { Write-Output $_.Exception.Message  $TargetURL+" "+$_.Exception.Message | Out-File -FilePath D:\SiteCreationLog.txt -Append } 


Hope this helps!

PowerShell script to change the content type for an existing document in Modern SharePoint Site

$
0
0

During our O365 Migration, we had an issue with removing old content type at library level since the items are attached with the old content type, hence I wrote script to change the old content type with the new content type for each items.

In this article, let us see how to change the document content type for an existing item without changing/modifying the Modified by and Modified columns.

Note: Before changing the content type of your document/item, make sure that the content type you are going to change to is associated with the list or library. Otherwise you will get a generic error when loading your page.

Step 1: Make sure SharePoint dlls are available in your local folder

Step 2: Please provide the required inputs such as site URL, List Name, User Name and Password

 #Load SharePoint CSOM Assemblies cls Add-Type -Path "C:\PS\dll\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\PS\dll\Microsoft.SharePoint.Client.Runtime.dll"     #Variables for Processing $SiteUrl = "https://ps.sharepoint.com/sites/test”
 $ListName="test" $UserName="test@test.onmicrosoft.com" $Password ="****"  #Setup Credentials to connect  $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force)) #Set up the context $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) $Context.Credentials = $credentials  try{     #Filter and Get the List Items using CAML $list = $Context.web.Lists.GetByTitle($ListName) $Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(1000);  $Items = $list.GetItems($Query); #$listItem= $list.GetItemById(97709); $Context.Load($list) $Context.Load($list.ContentTypes) $Context.Load($Items);  $Context.ExecuteQuery();   #Get the new content type ID for library/lsit     foreach($ct in $list.ContentTypes){    if($ct.Name -eq "Document"){        $contentTypeId= $ct.Id       }    }  Write-Host "New Content Type ID."+ $contentTypeId -ForegroundColor Green    foreach($listItem in $Items)    {   # Change the old content type with the new content type at item level and preserve the modified and Modified by       Write-Host "Item ID:"$listItem["ID"].ToString();      $Context.Load($listItem.ContentType)      $context.ExecuteQuery()      write-Host $listItem.ContentType.Name                         if ($listItem.ContentType.Name -eq "Working Document")                     {                     $listItem["ContentTypeId"] = $contentTypeId.StringValue                     $modifiedBy = $listItem["Editor"] #Editor is the internal name of the Modified By column                     $listItem["Editor"] = $modifiedBy                     $modified = $listItem["Modified"] #Modified is the internal name of the Modified column                     $listItem["Modified"] = $modified                     $listItem.Update()                                     }                                        }      $Context.ExecuteQuery()     write-host "Item Updated!"  -foregroundcolor Green  } catch{      write-host "$($_.Exception.Message)" -foregroundcolor red  }  

Hope this helps!

Quick Authentication from PnP PowerShell to access SharePoint

$
0
0

Hello everyone,

In this article we will see how to easily access SharePoint from PnP PowerShell by quick authentication (no need to provide username and password each time). This could help when there’s a need to run a scheduled task which access SharePoint. The first and foremost step to access SharePoint from PnP PowerShell is authentication. If we set this authentication default from your windows machine then we no need to provide username and password each time.

I’ve already published couple of articles on PnP PowerShell to setup your environment, please refer those if you are looking for initial setup

· How to Use PnP PowerShell in Windows 7 or Windows 8 Machine

· How to Connect to SharePoint Online Using PnP PowerShell and SharePoint Online Management Shell

Step 1: After successful setup, open Windows PowerShell

clip_image002

And I am going to access below SharePoint site through PnP PowerShell

clip_image004

Step 2: Using PnP command, I am accessing my SharePoint site as shown below, to know more about PnP commands visit here

clip_image006

As you can see, Windows PowerShell prompts and request for username & password. After providing right username & password we can have access to the SharePoint site. For testing, I just gave Get-PnPUser cmd

clip_image008

Step 3: In order to avoid this credential prompt, we can make use Credential Manager,

clip_image009

Step 4: In Credential Manager Window, click on “Add a generic credential

clip_image011

Step 5: Provide SharePoint site url (if you want only particular site collection, then specify the site name explicitly), credentials and click on OK

clip_image013

Step 6: Now I opened the new PowerShell window as shown in Step 1. And connected to my SharePoint site successfully without prompting for credential.

clip_image015

In this way we can run scheduled task or quickly access SharePoint site by avoiding giving credentials every time. I hope you enjoyed the article, thank you for reading.

Happy Coding

Ahamed

Viewing all 31 articles
Browse latest View live