I have a .net application where I want the ability to start and stop a Windows service running on the same computer. I was able to pull back the service's status using get-service without a problem, but doing start-service doesn't work. No error, just doesn't do anything. I tried this first without using the async Invoke option so that it looked more like the function at the bottom. When debugging locally, it does not work and does not error.
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();
}
}
Getting service status (this works):
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();
}
}
Sounds like you don't have permissions, one option is to set the execution policy
//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);
you can get the current user like so
WindowsIndentity.GetCurrent().Name
optionally try the new Host Builder, a new addition with.Net Core native, ie without topshelf
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((context, config) =>
{
// configure the app here.
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.