首页 文章

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

提问于
浏览
1

开门见山:

我正在开发一个应该在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文件中我可以看到这个错误:....术语安装-SPInfoPathFormTemplate不是已知的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.这可能是一个双跳问题,如果是这样,我怎么能解决它?

提前致谢!

1 回答

  • 0

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

    第一:服务从IIS运行,在应用程序池的高级属性中,“加载用户配置文件”设置设置为false . 当此设置为true时,powershell已成功运行 .

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

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

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

相关问题