简体   繁体   English

通过C#启动/停止Windows服务,并以管理员身份运行,而没有UAC提示窗口

[英]start / stop windows service via C# with run as admin without UAC prompt window

I need to start / stop a windows service from C# code at specific time everyday. 我需要每天在特定时间从C#代码启动/停止Windows服务。 So i have written a simple C# program. 所以我写了一个简单的C#程序。 My program only works when i run it as administrator. 我的程序只有在以管理员身份运行时才能运行。 Its fine I have written code to run my program as admin. 很好,我已经编写了代码以管理员身份运行程序。

Now i am stuck in the situation where my C# code runs the exe file as "Admin" but the UAC window appears with program wants to change settings etc msg. 现在我陷入了我的C#代码以“ Admin”身份运行exe文件但UAC窗口出现的情况, program wants to change settings etc

I need my c# code file runs under windows scheduler which means no human interaction is wanted. 我需要在Windows Scheduler下运行我的C#代码文件,这意味着不需要人工干预。 As for UAC window, user needs to select yes. 对于UAC窗口,用户需要选择“是”。

How can i get rid of that or work around so my program will execute and stop service completely pragmatically without any human interaction? 我该如何摆脱它或变通解决方案,以便我的程序在没有任何人工干预的情况下完全实用地执行和停止服务?

Create a version of your program that accepts a 创建您的程序的版本,该版本接受

Sam.exe /StopAndStopTheWindowsServiceINeedToSmack

On startup of your app, check for the command line switch. 在启动应用程序时,请检查命令行开关。 If present, then to the stop/start. 如果存在,则停止/开始。

Then create a scheduled task which runs your app with the command line option, and has the Run with highest privileges option set: 然后创建一个计划任务,该任务通过命令行选项运行您的应用,并设置了“以最高权限运行”选项:

在此处输入图片说明

Then use the Task Scheduler 2.0 API to programatically start the scheduled task. 然后,使用Task Scheduler 2.0 API以编程方式启动计划的任务。

Bonus Chatter: A chunk of code 额外的Chat不休:一小段代码

public Form1()
{
    InitializeComponent();

    //Ideally this would be in program.cs, before the call to Application.Run()
    //But that would require me to refactor code out of the Form file, which is overkill for a demo
    if (FindCmdLineSwitch("StopAndStopTheWindowsServiceINeedToSmack", true))
    {
        RestartService("bthserv"); //"Bluetooth Support Service"
        Environment.Exit(0);
    }
}

private bool FindCmdLineSwitch(string Switch, bool IgnoreCase)
{
    foreach (String s  in System.Environment.GetCommandLineArgs())
    {
        if (String.Compare(s, "/" + Switch, IgnoreCase) == 0)
            return true;
        if (String.Compare(s, "-" + Switch, IgnoreCase) == 0)
            return true;
    }
    return false;
}

And we restart the service: 然后我们重新启动服务:

private void RestartService(String ServiceName)
{
    TimeSpan timeout = TimeSpan.FromMilliseconds(30000); //30 seconds

    using (ServiceController service = new ServiceController(ServiceName))
    {
        try
        {
            service.Start();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message, "Error stopping service");
            return;
        }
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

        try
        {
            service.Start();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message, "Error starting service");
            return;
        }
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
}

Bonus: checking if you're running elevated: 奖励:检查您是否正在升高的状态:

private Boolean IsUserAnAdmin()
{
    //A user can be a member of the Administrator group, but not an administrator.
    //Conversely, the user can be an administrator and not a member of the administrators group.

    //Check if the current user has administrative privelages
    var identity = WindowsIdentity.GetCurrent();
    return (null != identity && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator));
}

Note : Any code released into public domain. 注意 :任何发布到公共领域的代码。 No attribution required. 无需注明出处。

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

相关问题 Win C#:在没有UAC提示的情况下以管理员身份运行app - Win C#: Run app as administrator without UAC prompt 在没有 UAC 的情况下使用管理员权限从 C# 运行 PsExec - Run PsExec from C# with admin right without UAC Windows服务启动和停止没有管理员权限 - Windows Service start and stop without admin privileges 如何创建一个 windows 应用程序,该应用程序应该在.Net C# 中以管理员权限运行,而不会一次又一次地提示 UAC? - How can I create a windows application that should run with admin rights in .Net C# without prompting UAC again and again? 是否可以在没有管理员权限的情况下安装,启动和停止Windows服务? - Is possible to install ,start and stop the windows service without admin rights? 如何在 Windows 2012r2 上使用提升的 UAC 权限运行我的 C# 服务? - How do I run my C# service with elevated UAC privileges on Windows 2012r2? 通过命令提示符“ C#”安装和卸载Windows服务 - Install and uninstall windows service via command prompt “C#” 强制 c# windows 服务始终作为系统运行,并且不允许非特权用户停止/启动 - Force c# windows service to always run as system and not allow stop/start by non-privileged users 使用C#在不使用UAC的情况下在窗口7中安装应用程序 - Install application in window 7 without UAC using C# 如何从C#启动/停止Windows服务 - How to start/stop a windows service from C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM