【问题标题】:Execute Powershell containing Sharepoint commands on remote server, from C#从 C# 在远程服务器上执行包含 Sharepoint 命令的 Powershell
【发布时间】:2017-07-30 20:06:24
【问题描述】:

直截了当:

我正在开发一项应该在 Sharepoint 服务器上运行的服务。 该服务应该能够在本地运行 Powershell 脚本,并且还可以在同一域中的一组 Sharepoint 服务器上运行相同的脚本。 该服务以本地服务器和远程服务器上的管理员用户身份运行。

powershell 脚本包含以下内容:

Try{
   Add-PSSnapin Microsoft.SharePoint.PowerShell
   Install-SPInfoPathFormTemplate -Path someInfoPath.xsn
}
Catch
{
    Add-Content C:\Temp\log.txt "$($_.Exception)" 
}

我曾尝试使用 C# 中的 Powershell 类来调用脚本,如下所示:

WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = machineAddress;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{ 
    ps.Runspace = runspace;
    ps.AddScript("Invoke-Expression C:\Temp\PowershellTest.ps1"); 
    var results = ps.Invoke();
    Console.WriteLine(results);
}  
runspace.Close(); 

这失败了,但没有向我的 C# 程序返回任何错误,但在 log.txt 文件中我可以看到这个错误: ....The Term Install-SPInfoPathFormTemplate is not a known cmdlet....

这告诉我 Add-PSSnapin Microsoft.SharePoint.PowerShell 命令不成功。

所以我尝试通过 C# 中的 Process.Start() 调用 Powershell,如下所示:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "powershell.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "Invoke-Command -ComputerName \\machineName -Path C:\Temp\PowershellTest.ps1

   using (Process exeProcess = Process.Start(startInfo))
   {
        exeProcess.WaitForExit();
   }

但是结果是一样的。

如果我在登录到远程桌面时尝试手动运行 powershell 脚本,如果我故意出错,它会完美执行或返回错误。

我怀疑是 Kerberos 双跳问题。

问题: 1. 是否可以远程运行 SharePoint InfoPath Services cmdlet (https://technet.microsoft.com/en-us/library/ee906553.aspx)? 2. 这可能是双跳问题吗?如果是,我该如何解决?

提前致谢!

【问题讨论】:

    标签: c# powershell sharepoint sharepoint-2013 kerberos


    【解决方案1】:

    好的,所以这个解决方案的技术设置中存在多个错误。

    首先:服务从 IIS 运行,并且在应用程序池的高级属性中,“加载用户配置文件”设置为 false。当设置为 true 时,powershell 运行成功。

    第二:为了能够在远程机器上调用 powershell 并避免双跳问题,我不得不使用 PSExec 并包含凭据。 (当然,传递凭据意味着我必须加密配置文件,因为它们存储在那里)

    最后但同样重要的是:运行应用程序池的用户没有适当数量的权限。这很难调试,因为 PSExec 返回了一条消息:“Powershell 退出,错误代码为 0”,但从我放入 powershell 的日志中,我可以看到 powershell 没有执行。

    这个问题的大部分解决方案都是技术性的,但我仍然认为与您分享结果是相关的。

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 2021-05-10
      相关资源
      最近更新 更多