首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从C#运行PowerShell脚本时,Add-PSSnapin的路径不正确

从C#运行PowerShell脚本时,Add-PSSnapin的路径不正确
EN

Stack Overflow用户
提问于 2019-04-02 20:47:11
回答 1查看 653关注 0票数 0

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

代码语言:javascript
复制
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命令将始终失败,并显示以下消息:

代码语言:javascript
复制
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."

运行时

代码语言:javascript
复制
$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#工具没有转发的路径或范围有关。尝试使用AddCommand的参数useLocalScope或其他参数没有产生任何结果(尽管我不确定这是否与路径有关)。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-02 22:49:54

SharePoint PowerShell管理单元仅提供64位版本。您的C#工具可能正在作为x86进程运行,因此会显示错误"not installed“。此外,您可能必须“以管理员身份”运行程序,因为某些命令需要这样做才能工作。

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

代码语言:javascript
复制
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.dll"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55475179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档