首页 > 解决方案 > 获取 PowerShell 脚本以在 Azure 上运行 SharePoint 命令

问题描述

我有一个应该在 SharePoint 上运行的 PowerShell 脚本。我一直在尝试在 Visual Studio 2019 上使用 C# 处理代码。我尝试了几种不同的方法,但都没有奏效。最终,我希望这些命令能够在 Azure 上部署的机器人上运行。

我已经Install-Module SharePointPnPPowerShellOnline在 PowerShell 和Install-Package SharePointPnPCoreOnline -Version 3.12.1908Visual Studio 上通过 PM 完成了。我的脚本在 PowerShell 上运行良好,但当我尝试使用 C# 调用脚本时它不起作用。我不断收到此错误 -System.Management.Automation.CommandNotFoundException: 'The term 'Connect-PnPOnline'无法识别为 cmdlet、函数、脚本文件或可运行程序的名称。

我找到了一些使用RunspaceConfigurationfrom 的解决方案System.Management.Automation.Runspaces。但似乎RunspaceConfiguration已从命名空间中删除,因为我找不到它。

我试图通过这样做来调用脚本

PowerShellInstance.AddScript(script)或者PowerShellInstance.AddCommand("Connect-PnPOnline").AddParameter()...但两者都不起作用。

两者都PowerShellInst.Invoke()返回pipeline.Invoke()Connect-Online无法识别的错误。我只在 Visual Studio 而不是 PowerShell 上收到此错误。

此代码有错误,pipeline.Invoke()Connect-PnPOnline无法识别第一个示例

{
    string text = System.IO.File.ReadAllText(@"C:\xxx\xxx\oo.ps1");

    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(text);

    Collection<PSObject> PSOutput = pipeline.Invoke();
    foreach (PSObject obj in PSOutput)
    {
        Console.WriteLine(obj.BaseObject.ToString());
    }
    Console.WriteLine("Done");

    runspace.Close();
} 

此代码有第二个示例无法识别PowerShellInst.Invoke()的错误Connect-PnPOnline

using (PowerShell PowerShellInst = PowerShell.Create())
{
    PowerShellInst.AddCommand("Connect-PnPOnline")
                    .AddParameter("site", "https://xxxxx.sharepoint.com/xxxxx").AddParameter("url", "site").AddParameter("UseWebLogin", "xxx")
                    .AddParameter("-Credentials", "xxxxx");
    Collection<PSObject> PSOutput = PowerShellInst.Invoke();
    foreach (PSObject obj in PSOutput)
    {
        Console.WriteLine("Read context of the Script: " + obj.BaseObject.ToString());
    }
}

这是我的示例脚本。

$site="https://xxxxx.sharepoint.com/xxxxx"

Connect-PnPOnline -url $site -UseWebLogin xxx -Credentials $xxxx

New-PnPWeb -Template "{xxxxxx}#ooo_projecttemplate" -Title $projecttitle -Url $projectnumber -Locale "777" -Description $theDescription -BreakInheritance

New-PnPGroup -Title $Title -owner $ID

似乎问题是当我尝试在 Visual Studio 上使用 C# 执行我的脚本时,无法识别 SharePoint 命令。有没有人有类似的问题或关于如何解决这个问题的任何想法?

感谢你的帮助。

标签: c#.netpowershellsharepoint

解决方案


按照以下官方指南导入模块。

https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/site-design-pnp-provisioning#upload-the-pnp-powershell-module-for-your-azure-function

要创建 PowerShell 脚本函数,请检查此线程

我的测试演示(Get-PnPWeb|选择标题,下面的屏幕截图未更新到最新脚本): 在此处输入图像描述


推荐阅读