【问题标题】:Calling Powershell script from windows service written in C#从用 C# 编写的 Windows 服务调用 Powershell 脚本
【发布时间】:2020-02-06 12:26:19
【问题描述】:

我有一个用 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. 虽然如果将其作为控制台应用程序运行,则相同的代码可以工作,但是在将其作为 Windows 服务运行时出现此错误。

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

【问题讨论】:

  • windows sservice 在其下工作的用户没有访问权限来访问您尝试访问的任何内容。
  • Windows 服务正在以本地用户身份运行,这也是管理员,如果这是与权限相关的问题,为什么当它作为控制台应用程序运行时会起作用?

标签: c# powershell windows-services


【解决方案1】:

您似乎做对了,但远程计算机配置不正确。 尝试执行 Commandlet

Enable-PSRemoting

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

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

【讨论】:

  • WinRM is already set up to receive requests on this computer.- 执行上述命令后得到这个,我认为这不是问题的原因,当我运行控制台应用程序并且访问远程计算机时也可以工作。
  • 可能是一个愚蠢的问题,但是在远程目标的管理员组中运行服务的用户是?
  • 是的,实际上我的目标是我正在运行的同一个系统,所以远程目标是运行服务的机器,是的,用户是管理员。
  • 您是否尝试过选中“与桌面交互”复选框(这被认为是不好的做法)以允许服务与其他上下文交互?
  • 我不知道为什么,但是您的建议有效,现在服务能够在远程计算机上调用 powershell 脚本。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多