【问题标题】:Path for Add-PSSnapin not correct when running PowerShell Script from C#从 C# 运行 PowerShell 脚本时,Add-PSSnapin 的路径不正确
【发布时间】:2019-08-23 19:17:01
【问题描述】:

我正在使用这样的 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 或其他参数没有产生任何结果(尽管我不确定这是否与路径有关)。

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

【问题讨论】:

    标签: c# powershell sharepoint path pssnapin


    【解决方案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"
    

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 2019-09-30
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多