从C#

时间:2019-04-02 12:47:11

标签: c# powershell sharepoint path pssnapin

我正在从C#工具运行PowerShell脚本,如下所示:

using (PowerShell pshell = PowerShell.Create())
{
    pshell.AddCommand(scriptFullPath);

    pshell.AddParameter("username", user);
    pshell.AddParameter("password", pass);

    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
    PSInvocationSettings settings = new PSInvocationSettings();
    settings.ErrorActionPreference = ActionPreference.Stop;

    pshell.Invoke(null, outputCollection, settings);
}

在我需要其他程序集的特殊Cmdlet之前,几乎所有内容在脚本中都可以正常工作。 Add-PSSnapin命令将始终失败,并显示以下信息:

Exception: The Windows PowerShell snap-in 'Microsoft.SharePoint.Powershell' is not installed on this computer.
Exception: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Cannot find path 'D:\dev\tool\Microsoft.SharePoint.dll' because it does not exist."

跑步时

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.SharePoint.Powershell"}
if ($snapin -eq $null)
{
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    Add-Type -Path "Microsoft.SharePoint.dll" 
    Add-Type -Path "Microsoft.SharePoint.Runtime.dll"
}

直接在PowerShell窗口中运行脚本时,一切工作都很好,所以我想它与未从C#工具转发的PATH或Scope有关。玩弄AddCommand的useLocalScope参数或其他参数不会产生任何结果(尽管我不确定这是否与路径有关)。

如何使脚本工作并找到外部程序集?

1 个答案:

答案 0 :(得分:1)

SharePoint PowerShell管理单元仅在64位中可用。您的C#工具可能正在作为x86进程运行,因此会给您错误“未安装”。另外,由于某些命令需要该命令才能运行,因此您可能必须以“以管理员身份”运行程序。

第二个错误是,很正确,默认情况下没有为SharePoint设置PATH变量。解决方法是指定.dll的完整路径(并更改安装的版本号),例如

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.dll"