Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Friday, October 23, 2020

PowerShell script to update Power BI Dataset parameters

In Power BI dataset or reports, parameters serve as a way to easily store and manage a value that can be changed after deployed. You could set up the parameters like database server name and database names inside Power BI solution and update through Power BI Settings as discussed before.

In this blog, we will use PowerShell to update the parameters. Here is the script to update the following two parameters on dataset named “MyReport” inside workspace named “My Workspace”. 

# Install-Module -Name MicrosoftPowerBIMgmt

# Connect to Power BI As admin

$User = "admin@mycompany.com"

$PW = "Password"

$SecPasswd = ConvertTo-SecureString $PW -AsPlainText -Force

$myCred = New-Object System.Management.Automation.PSCredential($User,$SecPasswd)

Connect-PowerBIServiceAccount -Credential $myCred


# Get Power BI Workspace ID

$WSID = Get-PowerBIWorkspace  -Scope Organization -Name 'My Workspace'| ForEach {$_.Id}


# Get Power BI Dataset ID

$DSIDMyReport = Get-PowerBIDataset -Scope Organization -WorkspaceId $WSIDAdmin | Where {$_.Name -eq "MyReport"} | ForEach {$_.Id}


# Construct Url with Dataset ID

$urlUpdateParams = "/datasets/" + $DSIDMyReport + "/Default.UpdateParameters"


# Update Parameters Body

$body = '{

  "updateDetails": [

    {

      "name": "DatabaseName",

      "newValue": "NewDBNamev"

    },

    {

      "name": "ServeName",

      "newValue": "myserver.database.windows.net"

    }

  ]

}'

$content = 'application/json'

# Update Dataset Parameters

Invoke-PowerBIRestMethod -Url $urlUpdateParams -Method Post -Body $body -ContentType $content

As enhancement, you could also use service principal as discussed in here to facilitate the login.

Thursday, June 18, 2020

Populate user office location for Power BI

There is a need to populate user office location for Power BI. Here is one of the quickest way to get this information trough AD Powershell.

I've quickly developed a script to have user office populate in a csv file and upload to SharePoint for Power BI to consume. Here is the script based on AD Powershell.


$ADUsers =  Get-ADUser -Filter *  -Properties physicalDeliveryOfficeName  | where physicalDeliveryOfficeName  -ne $null
$outputFile = "C:\Harry\Projects\SPCOE\Scripts\GetADUsers\Output\ADUsers.csv"

$rows = @()

foreach($ADUser in $ADUsers)
{
    $rows += New-Object -TypeName PSObject -Property @{                                                                                                                                   

                                            Name = $ADUser.Name
                                            UPN = $ADUser.UserPrincipalName 
                                            Office = $ADUser.physicalDeliveryOfficeName                                       

                                            } | Select-Object Name,UPN,Office

}

$rows | Export-Csv $outputFile  -NoTypeInformation -Force  -ErrorAction SilentlyContinue

Thursday, June 11, 2020

How to invoke Azure function inside PowerShell or Azure Runbook

The way PowerShell to call Azure function is same as call rest web service. There are few tips as below.
  1. Use client object module and add the module into PowerShell or Azure Runbook
  2. Azure function might have security configured and you will need to add "Access-Control-Allow-Origin"
  3. You might need to pause the result but in our case it is simple "Yes" or "No"
The example below can give you quick start.

# Add references for Runbook
Add-Type -Path  "C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.dll"
Add-Type -Path  "C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.Runtime.dll"

$spoSiteUrl ="https://yourcompany.sharepoint.com/sites/pubs"
$creds = Get-AutomationPSCredential -Name 'O365_svc'

# Load SharePoint online CSOM for email
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($spoSiteUrl)
$userName = $creds.UserName
$password = $creds.Password
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
$ctx.Credentials = $credentials
$ctx.AuthenticationMode = [Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default

$PubsId=12345
$RequestUrl='https://yurcompany.azurewebsites.net/api/PublicationLookup?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==&qry=canbepartiallyapproved&id='+$PubsId
write-Output $RequestUrl
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Credentials = $Context.Credentials
$WebSession.Headers.Add("Accept", "application/json;odata=verbose")
$WebSession.Headers.Add("Access-Control-Allow-Origin", "mycompany.sharepoint.com")
 
$Result="No"
#Invoke Rest Method
$Result = Invoke-RestMethod -Method Get -WebSession $WebSession -Uri $RequestURL
write-Output $Result $pubs.Id 

Thursday, October 10, 2019

Procedure to resolve the issue - cannot add SharePoint online list item with form does not exist error

We have found an issue that we could add new item to a SharePoint online list. The error is the form does not found. After debugging the issue, we identified that display item, edit item, and add item all have the same issue. Here is the details how to debug and fix the issue.

1. Verify three forms. If you understand how SharePoint works, you will know immediately that this should be the issue on SharePoint three form issue (NewForm.aspx, DidForm.aspx, and EditForm.aspx).  You can verify after open the site with SharePoint designer. 

2. Try to recreate the missing forms. The next step is to use SharePoint designer to add these three forms as described here. However, we got server error.

3. The next step is to migrate the same list from another place using Sharegate. The migration failed and has the following message.

"Unable to create web part 'Microsoft.SharePoint.WebPartPages.ListFormWebPart': A Web Part or Web Form Control on this Page cannot be displayed or imported. You don't have Add and Customize Pages permissions required to perform this action.. In Office 365, this is mainly caused by the farm setting "Custom Script" being deactivated."

Now we identified the root cause.

4. Enable the "Custom Script" on the site using the script described here. 

Connect-SPOService -Url https://mycompany-admin.sharepoint.com
Set-SPOSite -Identity https://mycompany.sharepoint.com -DenyAddAndCustomizePages 0 

5. The final step is either recreate the three forms from SharePoint designer or migrate content from another environment.

6. You might want to disable the "Custom Script" again suing Powershell.

Connect-SPOService -Url https://mycompany-admin.sharepoint.com
Set-SPOSite -Identity https://mycompany.sharepoint.com -DenyAddAndCustomizePages 1


We are not sure why the three forms lost in the first place but this blog will give you the procedure to fix the issue. 

Friday, January 25, 2019

PowerShell to create SharePoint online managed metadata terms from xml file

Our company started to SharePoint online governance plan and design the information architecture. One topic is to provide a global term for tagging and categorization. There are few good article to use PowerShell or C# to create terms from input file, however none of them can satisfy the requirement to create terms from Powershell with multiple levels of terms, and multiple termSet, and mutiple term groups.

I've modified the script we used previously for SharePoint on-premises and here is the code you could use for SPO.

#################################################################################
# Tod: Please update the following paremeters:
# $user        SharePoint admin user account like "harryc@mycompany.onmicrosoft.com"
# $siteUrl     SahrePoint onloine admin site url like "https://mycompany-admin.sharepoint.com/"
# Please install the SharePoint client components SDK - http://www.microsoft.com/en-us/download/details.aspx?id=35585 prior to running this script.

# Input Arguments
param([string]$userName,[string]$siteUrl)

[System.Net.ServicePointManager]::SecurityProtocol =[System.Net.SecurityProtocolType]::Tls12
Set-ExecutionPolicy -Scope Process -Confirm:$False -ExecutionPolicy Bypass -Force

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "../Assembly\Microsoft.SharePoint.Client.dll"
Add-Type -Path "../Assembly\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "../Assembly\Microsoft.SharePoint.Client.Taxonomy.dll"

#Specify tenant admin and URL
#$user = "harryc@mycompany.onmicrosoft.com"
#$siteUrl = "https://mycompany-admin.sharepoint.com/"
$user = $userName
$siteUrl = $siteUrl
$password = Read-Host -Prompt "Please enter your password" -AsSecureString

# Import term xml file
[xml]$importxml = Get-Content "..\Config\InputTerms.xml" -Encoding UTF8
#$Import.InnerXml
if ($importxml -eq $null) {
  write-host "Term creation file content is empty!"
  return

}

try{
        #Bind to MMS
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
        $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($user,$password)
        $ctx.Credentials = $creds
        $mms = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($ctx)
        $ctx.Load($mms)
        $ctx.ExecuteQuery()

        #Retrieve Term Stores
        $termStores = $MMS.TermStores
        $ctx.Load($termStores)
        $ctx.ExecuteQuery()

        #Bind to Term Store
        $termStore = $termStores[0]
        $ctx.Load($termStore)
        $ctx.ExecuteQuery()


        Foreach ($groupName in $importxml.Group.Name)
        {
            #Create Groups
            $group = $termStore.CreateGroup($groupName,[System.Guid]::NewGuid().toString())
            $ctx.Load($group)
            $ctx.ExecuteQuery()
            Write-Host "Create group - " $groupName;

            Foreach ($termSet in $importxml.Group.TermSet){
                #Create Term Sets
                $newTermSet = $group.CreateTermSet($termSet.Name,[System.Guid]::NewGuid().toString(),1033)
                $ctx.Load($newTermSet)
                $ctx.ExecuteQuery()
                Write-Host "Create termSet - " $termSet.Name;

                Foreach ($term in $termSet.Term){
                    #Create Terms
                    $newTerm = $newTermSet.CreateTerm($term.Name,1033,[System.Guid]::NewGuid().toString())
                    $ctx.Load($newTerm)
                    $ctx.ExecuteQuery()
                    Write-Host "Create term - " $term.Name;
                    if($term.Term -ne $null){
                        CreateChildTerms $ctx $newTerm $term
                    }
                }
          }
        }
}
catch [System.Exception]
{ 
    Write-Host "Exception:"  + $_.Exception.Message -foregroundcolor black -backgroundcolor yellow  
}


#############################################################
# Function to create sub-terms recursively
# $ctx        ClientContext
# $rootTerm   Parent term to create sub-term 
# $term       xml sub-term need to be created
#############################################################
function CreateChildTerms([Microsoft.SharePoint.Client.ClientContext]$ctx, [Microsoft.SharePoint.Client.Taxonomy.Term]$rootTerm, [System.Xml.XmlNode]$term)
{

       foreach ($childnode in $term.Term)
       {
             $addedTerm = $rootTerm.CreateTerm($childnode.Name, 1033, [System.Guid]::NewGuid().toString());
             $ctx.Load($addedTerm);
             $ctx.ExecuteQuery();
             Write-Host "Create child term - " $childnode.Name;

             # If sub-term need to be created, create recursively
             if($childnode.Term -ne $null){
                CreateChildTerms $ctx $addedTerm $childnode
             }
       }

}

There are many things we might need to development around terms like we did for SharePoint on-premises. Here is the list of the scripts in order to provide disaster recovery capability for terms.

1. Script to export the tenant term groups, termSets, and terms along with object GUID in xml file
2. Script to import the tenant term groups, termSets, and terms along with object GUID in xml file

We will keep you posted the progress on these scripts.

Produce to disable end users to create SharePoint online site and groups

Most companies will establish a SharePoint online site governance policy and provide a self provisioning process for sites and groups. So the question is how to disable end users to create site and groups? 
Microsoft provided the following two procedures.
  1. Manage site creation in SharePoint Online
  2. Manage who can create Office 365 Groups
Since the first step is straightforward, you can apply this quickly. The second step is tedious and I've modify the Microsoft PowerShell to make it easy. You will create the security group as instructed first. Then pass the group name to the PowerShell. The script will either print the configuration successfully completed or failed. Here is the modified script.

# You might need to set up your environemnt before running this script
#Install-Module AzureADPreview
#Import-Module AzureADPreview

# Input Arguments
param([string]$mySecurityGroupName)

Set-ExecutionPolicy -Scope Process -Confirm:$False -ExecutionPolicy Bypass -Force
[System.Net.ServicePointManager]::SecurityProtocol =[System.Net.SecurityProtocolType]::Tls12

Connect-AzureAD
$mySecurityGroup = $mySecurityGroupName #"SPCreator"
$myGroup = Get-AzureADGroup -SearchString $mySecurityGroup
$Id = $myGroup.ObjectId

$Template = Get-AzureADDirectorySettingTemplate | where {$_.DisplayName -eq 'Group.Unified'}
$Setting = $Template.CreateDirectorySetting()
$newSetting = Get-AzureADDirectorySetting

if ($newSetting -eq $null){
    New-AzureADDirectorySetting -DirectorySetting $Setting
    $newSetting = Get-AzureADDirectorySetting
}

$Setting = Get-AzureADDirectorySetting -Id (Get-AzureADDirectorySetting | where -Property DisplayName -Value "Group.Unified" -EQ).id

$flag = $Setting["EnableGroupCreation"]
Write-Output "Group created enabled before = $flag"

$Setting["EnableGroupCreation"] = $False
$flag = $Setting["EnableGroupCreation"]
Write-Output "Group created enabled after = $flag"

#$Setting["EnableGroupCreation"] = $True
$Setting["GroupCreationAllowedGroupId"] = (Get-AzureADGroup -SearchString $mySecurityGroup).objectid

Set-AzureADDirectorySetting -Id (Get-AzureADDirectorySetting | where -Property DisplayName -Value "Group.Unified" -EQ).id -DirectorySetting $Setting

$newSetting = Get-AzureADDirectorySetting 
#$newSetting.Values

foreach ($value in $newSetting.Values)
{
     if($value.Name -eq "GroupCreationAllowedGroupId"){
        if($Id -eq $value.Value){
            Write-Output "Only membesr of group named $mySecurityGroup can create groups now!"
        }
        else{
            Write-Output "Group named $mySecurityGroup not configured correct!"
        }
      }
}

If you need to disable users to create Yammer, planner or anything that would create SharePoint groups or site, you could further disable their license and restrict the creation.

SharePoint online site migration process across different tenants with both internal users and external users


Recently we have few requests to migrate SharePoint online site from one tenant to another and keep the same permission assignment. The challenge part is the site owners have invited many external users and we would need to keep the content with same permissions. There are seven major steps and here is the detailed procedures with some automation.





1. Original site analysis and report. This will include the following details.
    • Identify the site template - we need to create the destination site with same site template
    • Identify all the security internal AD groups used - we need to create same security groups in destination and add all the internal users
    • Identify all internal users - we need to create them in destination AD if not already and add to site
    • Identify all external users - we need to "add" them to destination site
    • Identify all breaking permission inheritance using Sharegate
Here I'll focus on the last part to get all external users as automated Powershell script to avoid tedious manual process. Other steps I'll provide some automation and tips in separate blogs. Here is the PowerShell to get all external users Email into a file so it can be used for next steps.

# GetUsersPnP.ps1   - Get all external users from a SPO site when passing site url
# $siteUrl                  -SPO site collection url
# $outputFileName  - Output file w/ all external users

param([string]$siteUrl,[string]$outputFileName)

Set-ExecutionPolicy -Scope Process -Confirm:$False -ExecutionPolicy Bypass -Force
Connect-PnPOnline -Url $siteUrl -Credentials (Get-Credential)

$exeUsers = Get-PnPUser |? LoginName -like  "*EXT*"
# If you remove the query, you will get all users on the site and handle internal users in destination site

$outputFileName = ".\Output\" + $outputFileName
$outputFile = $myinvocation.mycommand.path.Replace($MyInvocation.MyCommand.name,"") + $outputFileName

$rows = @()
foreach($exeUser in $exeUsers)
{
    $rows += New-Object -TypeName PSObject -Property @{                                                                                                                       
                                            LoginName = $exeUser.LoginName
                                            Email = $exeUser.Email                             
                                            } | Select-Object LoginName,Email
}

$rows | Export-Csv $outputFile  -NoTypeInformation -Force  -ErrorAction SilentlyContinue


2. Prepare destination site. This will include the following details.
    • Create site collection using the template from step #1
    • Create AD groups with same name as in step #1 and sync to Azure AD in destination
    • Create internal users in destination and add them to the AD groups using by the site
    • Add the security group to the site - this is optional but would be safe to ensure to migrate the groups

You could use PowerShell scripts to automate these steps. I can provide some of them in the future blog.

3. Invite external users from destination site. The purpose is to get all external users to the destination site so the migration will find the external users and migrate the permissions correctly. Since there is no easy to add all external users to the destination tenant and site, you could use the following PowerShell to invite external users and monitor if them accepted. 

The script will use the external user report generated from previous step #1.

# InviteExeUsersfromCSV.ps1 - Invite external users for a SPO site 
# $siteUrl                                  - SPO site collection url
# $outputFileName                   - Output file w/ all external users

# Input Arguments
param([string]$siteUrl,[string]$inputFileName)

Set-ExecutionPolicy -Scope Process -Confirm:$False -ExecutionPolicy Bypass -Force
Add-Type -Path ".\Assembly\Microsoft.SharePoint.Client.dll"
Add-Type -Path ".\Assembly\Microsoft.SharePoint.Client.Runtime.dll"

$inputFileName = ".\Input\" + $inputFileName
$CSVFile = $myinvocation.mycommand.path.Replace($MyInvocation.MyCommand.name,"") + $inputFileName
$users = Import-Csv $CSVFile

if ($users -eq $null) {
  write-host "User invitation file content is empty!"
  return
}

$userName = Read-Host -Prompt "Please enter your user name"
$Secure_String_Pwd = Read-Host -Prompt "Please enter your password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $Secure_String_Pwd)
$ctx.Credentials = $credentials
# Create request list
$userList = New-Object "System.Collections.Generic.List``1[Microsoft.SharePoint.Client.Sharing.UserRoleAssignment]"

# For each user, set role
ForEach($user in $users)
{
    $userRoleAssignment = New-Object Microsoft.SharePoint.Client.Sharing.UserRoleAssignment
    $userRoleAssignment.UserId = $user.Email
    #$userRoleAssignment.Role = [Microsoft.SharePoint.Client.Sharing.Role]::None
    $userRoleAssignment.Role = [Microsoft.SharePoint.Client.Sharing.Role]::View
    $userList.Add($userRoleAssignment)
    Write-Host "Request for user " $user.Email " to site - " $siteUrl
}

try
{
    # Send invites
    $message = "Please accept this invite to our SharePoint site. Thanks!"
    $res =[Microsoft.SharePoint.Client.Sharing.WebSharingManager]::UpdateWebSharingInformation($ctx, $ctx.Web, $userList, $true, $message, $true, $true)
    $ctx.ExecuteQuery()
    $Success = $res.Status
    $StatusMessage = $res.message
    Write-Host "Send invite Status " $Success
}
catch
{
    Write-Host "Error to invite users"
    $hasError = ($error[0] | out-string)
}

4. Finalize destination site. This will include the following steps.
    • Identify remaining external users who have not accepted the invitation
    • Identify the using mapping for migration
    • Add migration system account as site collection in destination site

You could set the invitation expiration days to 10 days for example (default is 90 days). After 10 days, identify any external users who have not accepted the invitation. You could use the following script similar to the one used step #1 run against destination site. The new script will report external users with flag "UserJoined" as "Y" or "N". 

You can compare and identify those users who have not accepted the invitation. You could either re-invite or map to replace them as either owner or migration system account during Sharegate migration.


# Input Arguments
param([string]$siteUrl,[string]$outputFileName, [string]$inputFileName)


################################################################################
#Set of test input data
#$siteUrl = "https://mycompany.sharepoint.com/sites/testsite"
#$outputFileName = ".\Output\NewExeUseresPnP.csv"
#$inputFileName = ".\Input\ExeUseresPnP.csv"
################################################################################

Set-ExecutionPolicy -Scope Process -Confirm:$False -ExecutionPolicy Bypass -Force
Connect-PnPOnline -Url $siteUrl -Credentials (Get-Credential)

$exeUsers = Get-PnPUser |? LoginName -like  "*EXT*"

$outputFileName = ".\Output\" + $outputFileName
$outputFile = $myinvocation.mycommand.path.Replace($MyInvocation.MyCommand.name,"") + $outputFileName


$inputFileName = ".\Input\" + $inputFileName
$inputFile = $myinvocation.mycommand.path.Replace($MyInvocation.MyCommand.name,"") + $inputFileName
$invitedUsers = Import-Csv $inputFile
$invitedUsers
$rows = @()

ForEach($user in $invitedUsers)
{
    $userJoined ="N"
    foreach($exeUser in $exeUsers)
    {
         if($exeUser.Email -eq $user.Email){
            $userJoined ="Y"
         }  
    }

    $newLoginName = "N/A"
    if($userJoined -eq "Y"){
        $newLoginName = $exeUser.LoginName
    }

    $rows += New-Object -TypeName PSObject -Property @{                                                                                                                              

                                                LoginName = $user.LoginName
                                                Email = $user.Email                                          
                                                UserJoined = $userJoined
                                                NewLoginName = $newLoginName
                                                } | Select-Object LoginName,Email,UserJoined, NewLoginName
}

$rows | Export-Csv $outputFile  -NoTypeInformation -Force  -ErrorAction SilentlyContinue

Write-host "Completed the site user report in " $outputFile -foregroundcolor black -backgroundcolor green


5. Content migration w/ permissions and user mapping. This will include the following steps.
    • Sharegate migration or other tools
    • Migrate whole site collection with permission mappping in previous step

 6. Make original site read only.
After content migrated, we should make the original site ready only so no updates will be made to the site. The easy way to do this is to apply the site policy as described here. Here are detailed steps.
    • Activate Site Policy site collection feature
    • Create one Site Policy and select "The site collection will be ready only when it closed"
    • In Site Closure and Deletion, associate the policy
    • In Site Closure and Deletion, select "Close this site now"
Your site will be ready only like below and you could archive or delete in the future. You could also add redirect if you need.




7. Clean up destination site and UAT. Here are the steps.
    • Make a backup of the site
    • Delete external users that should not be in the visitor group
    • Remove migration system account as site collection admin
    • Complete UAT
    • Remove the backup
    • Set up redirect from original site
    • Archive or delete original site

After content migrated, it's better to remove the external users invited to the SharePoint groups. In this case, all of them are invited to visitor group. Since we normally invite to the individual library, folder, or file, they should not have all view permission to whole site. This final step is to verify original site any external should not be in the visitor group, then remove them form the destination site.

Now you should have the site migrated to another tenant with permission mapped as original site.


Friday, January 11, 2019

Procedure to resolve error "The request was aborted: Could not create SSL/TLS secure channel." for SharePoint CSOM against SharePoint online

Recently, when I try to use SharePoint client object model (CSOM) to retrieve, update, and manage data in SharePoint online, I got the following error.

"The request was aborted: Could not create SSL/TLS secure channel." 

This is strange since we have been doing this type of PowerShell using CSOM against SharePoint online for few years. After working with Microsoft on this issue (#12681743), we identify the root cause is SharePoint online stopped to support SSL/TLS 1.0 since November 2018. This change has been gradually pushed to tenant gradually.

The solution to fix this issue is to add the following line in the beginning of the PowerShell script.

[System.Net.ServicePointManager]::SecurityProtocol =[System.Net.SecurityProtocolType]::Tls12

You could also to use the following line to allow different version of TLS to run the script.
[System.Net.ServicePointManager]::SecurityProtocol =[System.Net.SecurityProtocolType]::TLS -bor [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11  

Here is one example when we enable app SideLoading in your non-developer SharePoint online site collection.

[System.Net.ServicePointManager]::SecurityProtocol =[System.Net.SecurityProtocolType]::Tls12

# Add-Type dll.
# Get user name and password
# …
[Microsoft.SharePoint.Client.ClientContext]$cc = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spocreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)

$cc.Credentials = $spocreds
$sideLoadingEnabled = [Microsoft.SharePoint.Client.appcatalog]::IsAppSideloadingEnabled($cc);
#Add your commands here …
   
$cc.ExecuteQuery()


Bow the code runs without error.

Please note Microsoft may change the supported TLS version in the future, you may need to keep track the supported version.

Monday, April 16, 2018

Tips to use Azure Automation for SharePoint online with PowerShell


Azure Automation delivers a cloud-based automation and configuration service that provides consistent management across your Azure and non-Azure environments. It consists of process automation, update management, and configuration features. Azure Automation provides complete control during deployment, operations, and decommissioning of workloads and resources. This article provides a brief overview of Azure Automation and answers some common questions. For more information about the different capabilities, visit the links throughout this overview.

We have a project that requires a back end scheduled job using PowerShell scripts to process many SharePoint online list items and send notifications. We have evaluated the Azure function, Webjob, and Azure automation. Azure automation looks like the best fit. Since this is the first time we are using Azure automation, there are few tips we would like to share so you could jump start this good feature. You should check best practice here first before going forward.

1. How to import packages required for PowerShell?
Since we need to use Microsoft.SharePoint.Client CSOM packages, we need to to use two package dlls listed below.

Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll

This is the way to upload the packages to Azure. You need to zip the dlls into a single zip file. I've zipped them into one file named Microsoft.SharePoint.Client.zip.


Then search the "mudule" in the Azure automation account. Click "Add a mudule". Select the zip file you like to add. The module will be uploaded for you to use as listed below.



2. How to refer the dlls uploaded to module?
You can refer the dlls using the following syntax. Please note the uploaded zip file name "Microsoft.SharePoint.Client" in the path.

Add-Type -Path "C:\Modules\User\Microsoft.SharePoint.Client\Microsoft.SharePoint.Client.dll"


3. How to use encrypted password in the scripts?
In most cases Azure automation needs to connect to external system with user name and password. We could save the password in the Azure automation account object "Credentials". You can add a credential as in the below screenshot.



Then you can use the password in the PowerShell like this.

$creds = Get-AutomationPSCredential -Name 'halotest' 
$userName = $creds.UserName
$password = $creds.Password 

$cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
$ctx.Credentials = $cred


4. How to write the standard output?
You need to change "Write-Host" to "Write-Output" to print out to console. One example is listed below.

write-Output "Connection to SPO successfully " $web.Title

5. How to invoke other PowerShell from PowerShell?
You need to create PowerShell runbook for each PowerShell first. Then refer the other PowerShell like listed below. Please note the slash instead of back slash.

./AnotherPowerShelll.ps1 

Please note the PowerShell refereed need to be published first!

Now, you should have few PowerShell to run and configure as schedule job.