从 C# 在远程服务器上执行包含 Sharepoint 命令的 Powershell

Execute Powershell containing Sharepoint commands on remote server, from C#

开门见山:

我正在开发一项应该在 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 class 来调用这样的脚本:

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 脚本,它会完美执行,或者 returns 错误,如果我故意出错的话。

我怀疑是 Kerberos 双跳问题。

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

提前致谢!

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

首先:该服务 运行 来自 IIS,并且在应用程序池的高级属性中,设置 "Load user profile" 被设置为 false。将其设置为 true 时,powershell 运行 成功。

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

最后但并非最不重要:应用程序池 运行 所在的用户没有适当的权限。这很难调试,因为 PSExec 返回一条消息说:"Powershell exited with error code 0" 但是从我放入 powershell 的日志中,我可以看到 powershell 没有执行。

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