繁体   English   中英

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

[英]Calling Powershell script from windows service written in C#

我有一个用 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();
}

我不断收到以下错误: Connecting to remote server <computername> failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. Connecting to remote server <computername> failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. 虽然如果它作为控制台应用程序运行,相同的代码也能工作,但我在将它作为 Windows 服务运行时收到此错误。

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

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

Enable-PSRemoting

在提升的 Powershell 中的目标计算机上。 这应该配置 WinRm 服务以启用远程处理并添加用于远程处理的防火墙规则。 欲了解更多信息,请看这里:

https://docs.microsoft.com/en-us/p owershell/module/microsoft.powershell.core/enable-psremoting?view=powershell-7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM