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 

No comments:

Post a Comment