簡體   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