How to Install SharePoint PowerShell Module inside C# for Azure Function App

徘徊边缘 提交于 2019-12-07 22:13:12

问题


Just to manage expectations, I am new to PowerShell and to Azure Functions.

Since Azure Functions 2.x no longer supports PowerShell so I am trying to run my PowerShell scripts which requires SPO modules from C# (code below) I am having trouble running the Azure Function App because the PowerShell scripts needed the SPO modules. Anybody who knows how to install the needed modules inside C# PowerShell Instance like Runspace or anything the like? I am even on the right track here? Any comments is highly appreciated. Thank you all.

Sample Code:

 [FunctionName("TestFunction")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                var script = @"
Install-Module Microsoft.Online.SharePoint.PowerShell
Install-Module SharePointPnPPowerShellOnline

$url = '<SharePoint Url>'

$ListName = '<List Name>'

Connect-PnPOnline -Url $url -UseWebLogin 

$Fields = Get-PnPField -List $ListName  
$Items= Get-PnPListItem -List $ListName -PageSize 5000

$RowCtr = 1;

foreach($item in $items.FieldValues)
{
    #do something
    $RowCtr++;
}
";

                PowerShellInstance.AddScript(script);

                var results = PowerShellInstance.Invoke();
                //some other codes
        }
    }

回答1:


You can use Runspace within an Azure Function as shown in this example, lines 93-98. For modules, you can include them as part of the payload you deploy to your function app (recommended), or install them using Kudu.




回答2:


Once you upload your modules via the payload or Kudo, your script should work with a few modifications. The modules can be directly downloaded from the https://www.powershellgallery.com/ using Save-Module. After that, your script should work with a few modifications. According to https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/connect-pnponline?view=sharepoint-ps, -UseWebLogin is browser based. Alternatively, you can use the -Credentials parameter. Here is how you build a PSCredential object:

$secPassword = ConvertTo-SecureString "StringPassword" -AsPlainText -Force
$credential = [System.Management.Automation.PSCredential]::new("userName", $secPasswd)

We have a PowerShell Preview in Azure Functions 2.x. Please let me know if you would like to try it. You can reach me at francisco.gamino@microsoft.com.

Cheers,

Francisco



来源:https://stackoverflow.com/questions/54361668/how-to-install-sharepoint-powershell-module-inside-c-sharp-for-azure-function-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!