SharePoint 2016/2013/Online: How to Upload Files to SharePoint Document Libraries by PowerShell Automation

File upload operations are quite frequently used and often tricky when the SharePoint governance allows only SharePoint Client Side Technologies.

Recently I have come across a requirement in one of my assignments where an automated process is required to Sync the network shares with SharePoint.

This provides me the opportunity to write down the automation process using PowerShell +CSOM combination.

In this demo we will explore the PowerShell code to upload the file to SharePoint Online/On Premise Implementations which represents just a part of the complete automation process.

In order to setup this demo I have created as document library in SharePoint Online Site as shown below:

123

Let’s consider that we have a File Share somewhere on the network having files to be uploaded to the SharePoint Document Library

4

Now let’s explore the code step by step:

Step 1: In this step Client connection has been setup and the Client Context has been initiated.

The below is representing the connection to SharePoint Online Site but this will be little different in case if you want to initiate the connection with SharePoint On Premise site there will be a slight difference in the code.

For details you can visit to my earlier blogs at below URLs:

https://howtodowithsharepoint.wordpress.com/category/sharepoint-2013/sharepoint-online/

https://howtodowithsharepoint.wordpress.com/category/powershell-with-csom/

5

Step 2: In this step we will instantiate the Document Library Object that will provide us the handle on the desired document library in SharePoint Online Site.

This handle will let us allow getting reference of the desired folder in the document library. In this demo we are referring the Root Folder of the document library

Step 3: In this step we will explore the File System folder by using Get-ChildItem cmdlet on the using the specific Folder path

Step 4: In this step we will call another supporting function to upload the files to SharePoint Document Library

6

Inside UploadFile function-

Step 5: In this step File Object has been initialized using “System.IO” namespace. The file object will provide us the handle on files in the disk folder, open the file and read the content of the file in form of File Stream

Step 6: In this step we will add the file to the SharePoint Document Library folder (Root Folder in this case) as File Stream that we get it in Step 5

Step 7: Load File object & execute query to get it file actually uploaded to SharePoint Document Library

Step 8: Check in the file that has been uploaded in the Step 7

Step 9: This is showing the function call to “UploadFileToLibrary” function

7

That is all for the code.

In order to test this script we can either choose SharePoint (2016/2013/Online) Management Shell or Windows PowerShell.

Since in this demo I demonstrating the PowerShell in Conjunction with CSOM that I am going to run on client machines where we don’t have SharePoint Management Shell installed so I am going to use Windows PowerShell only.

Search for Windows PowerShell and launch the Windows PowerShell Command Prompt as shown below:

8

Refer the script & execute it

9

Provide password to when asked for

10

Once the PowerShell Script executes successfully, we can see the success messages printed on the Command Prompt

11

After the successful execution of the PowerShell script we can go back to the SharePoint Online Site and navigate to the document library that is the destination for these newly uploaded documents and sure enough we will get the documents

12

In case if you want to achieve additional automation scenarios you can execute this script as part of the Scheduled Task and that will further reduce human errors by executing the process automatically for you.

That is all for this demo.

Hope you find it helpful.

Advertisements

SharePoint 2016/2013/Online: How to Download SharePoint Files by PowerShell Automation

In this article we will explore the PowerShell way of downloading the files in SharePoint Document Libraries.

By adding some flavor of automation mechanism this technique could be very useful to the scenarios where we need to download documents in bulk in a schedule based job.

In order to setup this demo I have created a document library in my SharePoint Online Site, though this equally applicable to On Premise implementations of SharePoint.

I have added a new document library in SharePoint Online Site by the name “Prashant Documents” with a set of documents uploaded to it.

0.0.png

I have also set up a local folder on the disk drive which will act as destination folder for the files to be downloaded

0.1.png

Step 1: Initiate the Client Context

In order to get more information on Setting up Client Context & other Environmental Configurations, you may visit one of the earlier articles SharePoint Online: How to Install SharePoint Online Management Shell

1.png

Step 2: Instantiate & Load SharePoint Document Library Object

Step 3: Load the Root Folder in SharePoint Document Library which is containing the set of documents to be downloaded

Step 4: Using “OpenBinaryDirect” Method that is available in “Microsoft.SharePoint.Client.File” Class to read the file from SharePoint Document Library and save the File Stream to the disk location by using “CopyTo” method which is available in “System.IO.File” Class

2

Step 5: Call “DownloadFilesFromFolder” function that will download the files to the disk location

3

Step 6: On execution of this function Windows PowerShell Credential Prompt will appear where we have to specify the password to the login account

4.png

Step 7: Once the script executed successfully we can see the documents downloaded into the disk location

5.png

Hope you find it helpful.

SharePoint Online: How to Install SharePoint Online Management Shell

SharePoint Management Shell is a Windows PowerShell Module that allows managing SharePoint Users, Sites & Content in an efficient manner.

In this article we will see the steps to setup the development machines with “SharePoint Online Management Shell”.

First let’s look for the System Requirements to avoid any frustrating compatibility issues that might arise later on:

System Requirement

Supported Operating System
  • Windows 7 Service Pack 1
  • Windows 8
  • Windows Server 2008 R2 SP1
  • Windows Server 2008 Service Pack 2
  • Windows Server 2012
PowerShell
  • PowerShell 3.0

Steps to Install SharePoint Online Management Shell

Step 1: Visit the Url: https://www.microsoft.com/en-in/download/details.aspx?id=35588

Step 2: Click download button

1

Step 3: Select “sharepointonlinemanagementshell_4727-1200_x64_en-us.msi” file and click Next

2

Step 4: Run the “sharepointonlinemanagementshell_4727-1200_x64_en-us.msi” file

Step 5: Accept License Terms & Click Install Button

3

4

5

Step 6: Once the installation is complete, search for “SharePoint Online Management Shell” and launch it

6

This completes the installation of SharePoint Online Management Shell on our machine.

Now let’s try a few of the operations to verify the installation of SharePoint Online PowerShell Module

How to connect to SharePoint Online Services

Get current user credentials to connect to the SharePoint Online Services (assuming the user is having a valid SharePoint Online Account Credentials)

$userCredentials = Get-Credential

7

8

Import “Microsoft.Online.SharePoint.PowerShell” Powershell module to the Management Shell Console

Import-Module Microsoft.Online.SharePoint.PowerShell

9Connect to SharePoint Online Service by supplying Tenant Url and User Credential to the Connect-SPOService command

Connect-SPOService  -Url  https://prashantmbansal-admin.sharepoint.com -Credential $userCredentials

If you notice carefully the URL I have supplied to the Url Parameter in the above command, you will find “-admin” is added in the URL.

Actual URL of the Tenant is https://prashantmbansal.sharepoint.com but it is by convention that we much have to use “-admin” in the Host Header of URL in order to connect to the SharePoint Online Services.

That is why we have to specify the “https://prashantmbansal-admin.sharepoint.com” as Tenant URL.

10

If we forgot to follow this convention we might encounter the following error:

11

How to get the list of all the SharePoint Sites lies under current Tenancy

Once we are successfully able to Connect to SharePoint Online Services we can perform different operations on the site such as getting a list of all the SharePoint Sites available with in current tenancy by using the following command.

Get-SPOSite

12

This is just the first step to Start with PowerShell Development for the SharePoint Online Sites, but the possibilities are limitless, especially when we can combine the SharePoint Client Object Model with PowerShell Scripting Environment.

We will explore the details on CSOM based Solutions driven by PowerShell Scripts in future articles.

Hope you find it helpful.

Office 365: Security Groups Management using Powershell

Security Groups are the crucial part of any system as they define the Authorization on the available resources for the Users requesting access. They are also important to categorize permission boundaries for the set of users at once. So it is really important to streamline the process of managing Security Groups for any system.

Though the management activities are repetitive and boring if we need to repeat same steps again and again over the period of time.

Thankfully we can automate these repetitive tasks using PowerShell Scripts which can take inputs from the CSV or Text Files for the input values and perform necessary actions.

In this article we will discuss the automation scripts required for managing Security Groups in Office 365 using PowerShell.

If you want to follow along then the prerequisite for this article are:

  • Having a O365 Account created
  • PowerShell for Office 365 configured

If the above prerequisites does not meet then I would recommend you to read one of my earlier article “Office 365: How to Configure PowerShell for O365” to get to know the steps of installing prerequisites.

Lets’ login to O365 Account and visit the Admin Center

1

Navigate to Admin Center by clicking the “Admin” Tile on the Application Dashboard as shown below

2

Now in the upcoming sections we will see to the respective PowerShell Commands to deal with each of the management tasks

How to Add new Security Groups

Navigate Admin Center => Groups

For the first time in my case there are no security groups are present since this is a new O365 Account

3

Run “New-MsolGroup” command where “DisplayName” specify the name of the Security Group and “Description” specify the description for the group as shown below

New-MsolGroup -DisplayName “Test Security Group” -Description “This is created for testing.”

4

Once the command gets executed successfully, navigate Admin Center  => Groups to verify that new group has been added.

It is worth to note that “Default Group Type” for any group added using the above command will be “Security”

5

 How to export all Security Groups

We can export all the Security Groups from the O365 account by using “Get-MsolGroup” command as shown below

Get-MsolGroup

6

Once the command is executed successfully we can see the details of all the available Security Groups on the Host Window. Alternatively we can export the results to text files by piping the results to “Out-File” command.

How to export all Security Groups filtered by Group Properties

We can export a filtered set of Security Groups from the O365 account based on any property of the Group. In the following example I am using “DisplayName” property to filter the results as shown below

Get-MsolGroup | Where-Object {$_.DisplayName -eq “Test Security Group”}

7

Once the command is executed successfully we can see the details of the specific Security Groups matching the filter criteria

How to export all Security Groups filtered by Group Type

We can export a Security Groups based on its type also by using “GroupType”. In the following example we are going to filter all Security Groups which are of type “Security” from the O365 account.

Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

8

Once the command is executed successfully we can see the details of all the Security Group of type “Security” and with DisplayName = “Test Security Group”

 How to Add Users to Security Groups

Run the following command to check the existing members which are present in the Security Group

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Get-MsolGroupMember -GroupObjectId $securityGroup.ObjectId

9

Once the command executed successfully we will get the list of Users already added to the group

We can see the same information by Editing the Group with in the Browser as shown below:

10

11

We can add new members to the Security Group by using the following command

Create Object required Security Group

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Create Object of the member depicted by “UserPrincipalName” parameter that needs to be added to the group

$member = Get-MsolUser -UserPrincipalName spdev001@spdevs001.onmicrosoft.com

Then use the following command to add the member to the group by specifying Group Object ID & Member Object ID

Add-MsolGroupMember -GroupObjectId $securityGroup.ObjectId -GroupMemberType “User” -GroupMemberObjectId $member.ObjectId

12

Once the command gets executed successfully we can see a new member has been added to the group.

We can verify the result of operation by using PowerShell Command

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Get-MsolGroupMember -GroupObjectId $securityGroup.ObjectId

13

We can also verify the result of operation by Browser as shown below

14

15

How to remove Users from Security Groups

We can we remove the Users from specific security group by using following set of commands

Create the Object of the respective group from which the user needs to be removed

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Create the object of the respective member that needs to be deleted from the group

$member = Get-MsolUser -UserPrincipalName spdev001@spdevs001.onmicrosoft.com

Then we can use “Remove-MsoLGroupMember” command to remove the member depicted by “Groupmemberobjectid” parameter from the group depicted by “GroupObjectId” parameter as shown below

Remove-MsoLGroupMember -GroupObjectId $securityGroup.ObjectId -GroupMemberType User -Groupmemberobjectid $member.ObjectId

16

Once the command gets executed successfully we can see the respective member gets deleted from the Security Group in question.

Now we can verify the delete operation by using the following PowerShell Command

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Get-MsolGroupMember -GroupObjectId $securityGroup.ObjectId

17

Or we can verify the same via Browser by Editing the Security Group as shown below

18

19

How to Remove Security Groups

We can use the following command to remove the Security Groups

Create object to the respective group

$securityGroup = Get-MsolGroup -GroupType “Security” | Where-Object {$_.DisplayName -eq “Test Security Group”}

Execute “Remove-MsolGroup” command to remove the group depicted by “objectid” parameter as shown below

Remove-MsolGroup -objectid $securityGroup.ObjectId

On execution this command will ask you for the confirmation on delete action

Enter your choice “Y” to continue “N” to cancel

20

21

Once the command is executed successfully we can go back to Groups section in Admin Center to verify the Delete Action

22

All of the above tasks can be automated by incorporating the CSV files to receive input from and perform the respective actions.

Hope you find it helpful.

Office 365: User Management using Powershell

In this article we will discuss some of the useful PowerShell Commands for managing Users in Office 365 (O365)

If you want to follow along then the prerequisite for this article are:

  • Having a O365 Account created
  • PowerShell for Office 365 configured

If the above prerequisites does not meet then I would recommend you to read one of my earlier article “Office 365: How to Configure PowerShell for O365” to get to know the steps of installing prerequisites.

  • Login to O365 Portal

1

  • Click on the Admin Center Tile

2

  • Click on “Active Users” navigation link under “Users” in the left navigation

Currently we can see only one Active User “Prashant Bansal”.

Since this is a free trail account so we cannot have more than one user here, but if you go for a paid plan then you can get multiple users as well.

3

Now in the following sections we will be looking into some of the useful operation and corresponding PowerShell commands regarding User Management

Export All Users

Command

Get-MsolUser

Usage

This command returns all the active users present in your O365 Account

Output

4

5

Export All Users with matching filter

Let’s see some of the properties of the User Profile available for every User added. Based on these properties we can export filtered set of Users. Lets’ check for the User properties first –

  • Select the User
  • Click Edit on the Profile Card on the right

6

  • Expand Additional Details
  • I have updated the User properties and now going to filter the Users based on “Job Title” property

7

Command

Get-MsolUser -Title “SharePoint Technical Consultant”

Usage

This command export all the Users where “Job Title = SharePoint Technical Consultant”

Output

8

 Export All Users with matching filter and selected properties

Command

Get-MsolUser -Title “SharePoint Technical Consultant” | Select DisplayName

Usage

This command export only “Display Names” for all the Users where “Job Title = SharePoint Technical Consultant”

Output:

9

Export All Users with matching filter and selected properties to a file

Command

Get-MsolUser -Title “SharePoint Technical Consultant” | Select DisplayName > “C:\SharePoint-Online-User-Data.txt”

Usage

This command export only “Display Names” for all the Users where “Job Title = SharePoint Technical Consultant” to a Text File at the specified path

Output

10

Create New Users

Command

New-MsolUser -UserPrincipalName “spdev002@spdevs001.onmicrosoft.com” -DisplayName “Prashant Bansal New User” -LastName “New User” -LicenseAssignment “spdevs001:DEVELOPERPACK” -UsageLocation “IN”

Usage

This command Adds a new User to the O365 Account specified by parameter “UserPrincipalName” and sets its basic properties like “Display Name, Last Name” and so on. It also assigns the license to the user specified by the parameter “LicenseAssignment”.

It is important to note that passing location information as specified by the parameter “UsageLocation” is mandatory as this is used by Microsoft for tracking the location where the service is consumed. This valid value for this parameter could be a two letter country code like for India it should be “IN”

If I execute this command I would get the following error since a free trail O365 account grant me a Single User license only.

If I am having proper license supporting multiple Users, this command would add a new User to my O365 Account.

Output

11

Modify Existing Users

Command

Set-MsolUser -UserPrincipalName “spdev001@spdevs001.onmicrosoft.com” -LastName “Mohan Bansal” -DisplayName “Prashant Mohan Bansal”

Usage

Using this command we can modify an existing User in our O365 Account specified by parameter “UserPrincipalName” and providing its properties like “Display Name, Last Name” and so on that needs to be updated.

Output

12

Once update is performed it might take a couple of minutes to take effect in O365 Account.

User Properties before update command executed:

13

User Properties after update command executed:

14

15

That all for this article on User Management using PowerShell for O365.

All of the above Operations can be automated and using same PowerShell Development paradigms as we followed for On Premise SharePoint Implementations.

Hope you find it helpful.