繁体   English   中英

如何在 .net 核心应用程序中使用 powershell 启动 Windows 服务?

[英]How to start a Windows service using powershell in a .net core application?

我有一个 .net 应用程序,我希望能够启动和停止在同一台计算机上运行的 Windows 服务。 我能够毫无问题地使用 get-service 拉回服务的状态,但是执行 start-service 不起作用。 没有错误,只是什么都不做。 我首先尝试了这个,没有使用 async Invoke 选项,这样它看起来更像底部的 function。 在本地调试时,它不起作用,也不会出错。

using System.Management.Automation;

        private async static Task EditService(string serviceName, string command)
        {
            using (PowerShell PowerShellInst = PowerShell.Create())
            {
                //PowerShellInst.AddCommand(command).AddParameter("Name", serviceName);
                //I tried surrounding serviceName in quotes (but it has no spaces)
                PowerShellInst.AddScript("Start-Service -Name " + serviceName);

                await PowerShellInst.InvokeAsync();
            }         
        }

获取服务状态(这有效):

 public static string GetServiceStatus(string serviceName)
        {            

            using (PowerShell PowerShellInst = PowerShell.Create())
            {
                PowerShellInst.AddScript("Get-Service " + serviceName);

                Collection<PSObject> PSOutput = PowerShellInst.Invoke();

                if (PSOutput == null || PSOutput.Count == 0)
                    return "Unknown";
                else
                    return PSOutput.First().Properties["Status"].Value.ToString();                
            }            
        }

听起来您没有权限,一种选择是设置执行策略

//in powershell
 powershell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted")
.AddParameter("Scope","CurrentUser");

//or using the command prompt like so:
 string powerShellCmd = "/c powershell -executionpolicy unrestricted C:\somePowerShellScript.ps1";
System.Diagnostics.Process.Start("cmd.exe",powerShellCmd);

你可以像这样得到当前用户

WindowsIndentity.GetCurrent().Name

可选择尝试新的 Host Builder,这是一个带有 .Net Core 原生的新增功能,即没有topshelf

 public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureAppConfiguration((context, config) =>
            {
                // configure the app here.
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });

暂无
暂无

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

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