Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6981753
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T18:11:53+00:00 2026-05-27T18:11:53+00:00

OK, I can’t fully decide if this is better asked on ServerFault or SO,

  • 0

OK, I can’t fully decide if this is better asked on ServerFault or SO, but I think this is more of a programming question at heart…(you may disagree)

I’m trying to wrap up all sorts of deployment activities into a single console application, then execute it with appropriate parameters with the TeamCity build Command Line runner. However, attempting to stop/start/install Windows services on a remote machine seems to be a tricky business using ServiceController from a process that can’t run with elevated permissions.

At this point, it might actually be the easiest method to execute Powershell scripts using Invoke-Command on each remote host. (of course, allowing this is a different security hole) than disabling UAC or other options…

Would anyone care to venture an opinion of what methodology would be the best way to proceed?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T18:11:54+00:00Added an answer on May 27, 2026 at 6:11 pm

    OK, I created a Powershell-based service controller class to allow an application running without elevated permissions to control remote services.

    Here it is:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //
    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    
    namespace PowershellBasedServiceControl
    {
        // All the relevant bits came from this article: http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx
        // if script execution fails, try running 'Enable-PSRemoting' using Powershell as an admin on the target host
    
    public class PowershellServiceController
    {
        public bool StartService(string serviceName, string remoteHost)
        {
            return StartService(serviceName, remoteHost, String.Empty, String.Empty);
        }
    
        public bool StartService(string serviceName, string remoteHost, string remoteUserName, string remotePassword)
        {
            bool result = false;
            string execOutput = ExecuteScript(BuildStartServiceScript(serviceName, remoteHost, remoteUserName, remotePassword, false));
            result = execOutput.StartsWith("0");
            if (!result)
                Console.WriteLine(execOutput);
            return result;
        }
    
        public bool StopService(string serviceName, string remoteHost)
        {
            return StopService(serviceName, remoteHost, String.Empty, String.Empty);
        }
    
        public bool StopService(string serviceName, string remoteHost, string remoteUserName, string remotePassword)
        {
            bool result = false;
            string execOutput = ExecuteScript(BuildStopServiceScript(serviceName, remoteHost, remoteUserName, remotePassword, false));
            result = execOutput.StartsWith("0");
            if (!result)
                Console.WriteLine(execOutput);
            return result;
        }
    
        string ExecuteScript(string scriptText)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
            // add an extra command to transform the script
            // output objects into nicely formatted strings
            // remove this line to get the actual objects
            // that the script returns. For example, the script
            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");
            // execute the script
            Collection<PSObject> results = pipeline.Invoke();
            // close the runspace
            runspace.Close();
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
        }
    
        string BuildStartServiceScript(string serviceName, string remoteHost, string remoteUserName, string remotePassword, bool echoScript)
        {
            StringBuilder script = new StringBuilder();
            if (!String.IsNullOrEmpty(remoteUserName))
            {
                script.AppendLine("$block = {");
                script.AppendLine("$returnCode = 1");
                script.AppendLine("try {");
                script.AppendLine(String.Format("$service = \"{0}\"", serviceName));
                script.AppendLine("$serviceController = (new-Object System.ServiceProcess.ServiceController($service,\"localhost\"))");
                script.AppendLine("if($serviceController.Status -notlike 'Running') {");
                script.AppendLine("$serviceController.Start()");
                script.AppendLine("$serviceController.WaitForStatus('Running',(new-timespan -seconds 120))");
                script.AppendLine("if ($serviceController.Status -eq 'Running') { ");
                script.AppendLine("$returnCode = 0 }");
                script.AppendLine("} else { ");
                script.AppendLine("$returnCode = 0 } }");
                script.AppendLine("catch {");
                script.AppendLine("return 1");
                script.AppendLine("exit }");
                script.AppendLine("return $returnCode}");
                script.AppendLine("");
    
                script.AppendLine(String.Format("$pass = convertto-securestring \"{0}\" -asplaintext -force", remotePassword));
                script.AppendLine(String.Format("$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist \"{0}\",$pass", remoteUserName));
    
                script.AppendLine(String.Format("$res = Invoke-Command -computername \"{0}\" -Credential $mycred -scriptblock $block", remoteHost));
                script.AppendLine("return $res");
            }
            if (echoScript)
                Console.WriteLine(script.ToString());
            return script.ToString();
        }
    
        string BuildStopServiceScript(string serviceName, string remoteHost, string remoteUserName, string remotePassword, bool echoScript)
        {
            StringBuilder script = new StringBuilder();
            if (!String.IsNullOrEmpty(remoteUserName))
            {
                script.AppendLine("$block = {");
                script.AppendLine("$returnCode = 1");
                script.AppendLine("try {");
                script.AppendLine(String.Format("$service = \"{0}\"", serviceName));
                script.AppendLine("$serviceController = (new-Object System.ServiceProcess.ServiceController($service,\"localhost\"))");
                script.AppendLine("if($serviceController.Status -notlike 'Stopped') {");
                script.AppendLine("$serviceController.Stop()");
                script.AppendLine("$serviceController.WaitForStatus('Stopped',(new-timespan -seconds 120))");
                script.AppendLine("if ($serviceController.Status -eq 'Stopped') { ");
                script.AppendLine("$returnCode = 0 }");
                script.AppendLine("} else { ");
                script.AppendLine("$returnCode = 0 } }");
                script.AppendLine("catch {");
                script.AppendLine("return 1");
                script.AppendLine("exit }");
                script.AppendLine("return $returnCode}");
                script.AppendLine("");
    
                script.AppendLine(String.Format("$pass = convertto-securestring \"{0}\" -asplaintext -force", remotePassword));
                script.AppendLine(String.Format("$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist \"{0}\",$pass", remoteUserName));
    
                script.AppendLine(String.Format("$res = Invoke-Command -computername \"{0}\" -Credential $mycred -scriptblock $block", remoteHost));
                script.AppendLine("return $res");
            }
            if (echoScript)
                Console.WriteLine(script.ToString());
            return script.ToString();
        }
    }
    

    }

    Here’s how you would use it in a console app:

    class Program
    {
        static void Main(string[] args)
        {
            PowershellServiceController runner = new PowershellServiceController();
            if (runner.StartService("w3svc", "myremotehost.com", "myusername", "mypassword"))
                Console.WriteLine("Service was started successfully");
            else
                Console.WriteLine("Failed to start remote service");
            Console.WriteLine("Press ENTER to quit");
            Console.ReadLine();
        }
    }
    

    Hopefully someone else finds this useful.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can I run this in a Windows command prompt like I can run it
Can anybody help me? What should be the datatype for this type -07:00:00 of
can someone explain why the compiler accepts only this code template<typename L, size_t offset,
Can't figure out how to do this in a pretty way : I have
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
can anyone tell me why this doesn't work? db = openOrCreateDatabase(database.db, SQLiteDatabase.CREATE_IF_NECESSARY, null); db.setLocale(Locale.getDefault());
Can't work out a way to make an array of buttons in android. This
Can anyone help me trying to find out why this doesn't work. The brushes
can someone show me the regex for this preg_match. I want to make sure
Does anyone know how can I replace this 2 symbol below from the string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.