[英]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.