使用Windows Service运行Powershell脚本时出现问题(错误代码= 5)

时间:2019-01-24 06:34:51

标签: c# windows powershell windows-services

我已经用C#创建了Windows服务,并添加了一个powershell脚本来执行OnStart()。尝试运行该脚本,并引发了“错误级别5:访问被拒绝”。如何使用Admin特权运行powershell脚本,这将帮助我绕过此问题。

protected override void OnStart(string[] args)
    {
        while(!Debugger.IsAttached)
        {
            System.Threading.Thread.Sleep(1000);
        }
        WriteToFile("Service is started at " + DateTime.Now);

        int errorLevel;
        try
        {
            string ps = @"C:/Projects/E/CreateSiteCollection.ps1";
            ProcessStartInfo processInfo;
            Process process;

            processInfo = new ProcessStartInfo("powershell_ise.exe", ps);
            process = Process.Start(processInfo);
            process.WaitForExit();

            errorLevel = process.ExitCode;
            process.Close();
        }
        catch(Exception ex)
        {
            WriteToFile(ex.InnerException.ToString());
        }

        WriteToFile("Service Completed at " + DateTime.Now);

    }

0 个答案:

没有答案