Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从用C编写的windows服务调用Powershell脚本#_C#_Powershell_Windows Services - Fatal编程技术网

C# 从用C编写的windows服务调用Powershell脚本#

C# 从用C编写的windows服务调用Powershell脚本#,c#,powershell,windows-services,C#,Powershell,Windows Services,我有一个用C#编写的windows服务,它使用下面的代码调用其中的powershell脚本: using (Runspace runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); using (var powershell = PowerShell.Create()) { powershell.Runspace = runspace; powershell.AddCo

我有一个用C#编写的windows服务,它使用下面的代码调用其中的powershell脚本:

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();
    using (var powershell = PowerShell.Create())
    {
        powershell.Runspace = runspace;
        powershell.AddCommand("Invoke-Command")
          .AddParameter("ComputerName", remoteComputer)
          .AddParameter("FilePath", scriptPath)
          .AddParameter("ArgumentList", new object[] { credential,IndexList,FilePath });
        psOutput = powershell.Invoke();
    }
    runspace.Close();
}

我不断发现以下错误:

连接到远程服务器失败,错误消息如下:访问被拒绝。有关更多信息,请参阅关于远程故障排除帮助主题。
虽然相同的代码可以在作为控制台应用程序运行时使用,但我在作为windows服务运行时遇到了这个错误


我在这里做错了什么吗?或者有另一种方法可以在windows服务中调用powershell脚本?

看起来您做得不错,但远程计算机的配置不正确。 尝试执行Commandlet

Enable-PSRemoting
在提升的powershell中的目标计算机上。 这将配置WinRm服务以启用远程处理,并为远程处理添加防火墙规则。 有关更多信息,请查看此处:


用户,windows S服务在该用户下工作,对您试图访问的内容没有访问权限。Windows服务正在以本地用户身份运行,这也是管理员身份。如果这是与权限相关的问题,那么当它作为控制台应用程序运行时,为什么会起作用?
WinRM已设置为在此计算机上接收请求
-执行后获取此信息上面的命令和我认为这不是问题的原因,当我运行console应用程序时,这也是访问工作的远程计算机的原因。可能是一个愚蠢的问题,但是在Administrators组中运行服务的用户是远程目标吗?是的,实际上,我的目标是我运行的同一个系统,因此远程目标是运行服务的机器,是的,用户是管理员。您是否尝试选中“与桌面交互”复选框(这被认为是错误的做法)以允许服务与其他上下文交互?我不知道为什么,但您的建议奏效了,现在服务可以在远程计算机上调用powershell脚本。谢谢。