Search code examples
c#windowsservicewmi

Control a service on a remote computer with only a local admin user (with powershell or/and c#)


I'm user in the active directory and there is a remote Computer outside this active directory. I want to start and stop a service on this computer. Of course a have the credentials of the local admin.

var startService = new Process
{
    StartInfo =
    {
        FileName = "sc.exe",
        Arguments = String.Format("{0} {1} {2}", "\\192.168.0.5", "stop", "TestService"),
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        UserName = "user",
        Password = securePassword,
        Domain = "localhost"
    }
};

try
{
    startService.Start();
}
catch (Exception e)
{
    return false;
}

It throws an exception, that the crentials are wrong.

Unknown Username or Bad Password

I tried to set StartInfo.Domain to the remote computer name, but this didn't work either.

Need some help here.


Solution

  • Remote side

    Enable-PSRemoting -Force
    

    Client side

    Invoke-Command -ComputerName ServerName -Credential Get-Credential -ScriptBlock {ls c:\}
    

    In ScriptBlock I can use the e.g. Get-Service Command to control a service on the remote side.

    In C# it locks like this

    // Install-Package System.Management.Automation 
    var credential = new PSCredential("User", securePassword);
    
    PowerShell ps = PowerShell.Create();
    ps.AddCommand("Invoke-Command");
    ps.AddParameter("ComputerName", "ComputerName");
    ps.AddParameter("Credential", credential);
    ps.AddParameter("ScriptBlock", ScriptBlock.Create("Get-Service -Name ServiceName"));
    
    var result = ps.Invoke();
    
    dynamic temp = result.First();
    var status = temp.Status;