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



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

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

可选择地尝试新的主机生成器,这是。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>();
});

最新更新