Ps command not running under windows service

57 Views Asked by At

When trying to run a ps command inside a windows service it returns me an error:

Get-LocalUser : 'Get-LocalUser' not recognized as cmdlet, function, script file or program. Verify if the file path is correct and try again. C:\Users\Admin\source\repos\ps.test\bin\Debug\GetLocalUserv2.ps1:1 caractere:1

  • Get-LocalUser
  •   + CategoryInfo          : ObjectNotFound: (Get-LocalUser:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
    
    

But when I run it as a console project it runs ok! Is there any windows limitation running some ps commands inside a win service?

using System.Diagnostics;
using System;
using System.ServiceProcess;
using System.Management.Automation;
using System.Timers;
using System.IO;
using System.Reflection;

namespace ps.test
{
    public partial class Service1 : ServiceBase
    {
        private static string localpath;
        private static string logPath;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            localpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            logPath = Path.Combine(localpath, "log.txt");
            File.AppendAllText(logPath, "start->"+DateTime.Now.ToString("yyyyMMdd:HHmmss") + Environment.NewLine);
            // Set up a timer that triggers every minute.
            Timer timer = new Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Start();
        }
        public void OnTimer(object sender, ElapsedEventArgs args)
        {
            File.AppendAllText(logPath, DateTime.Now.ToString("yyyyMMdd:HHmmss") + Environment.NewLine);
            string output;
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            string batFile = Path.Combine(localpath, "GetLocalUserv2.bat");
            startInfo.FileName = batFile;
            //if (script.Parameters != null && script.Parameters.Length > 0)
            //    startInfo.Arguments = string.Join(" ", script.Parameters);
            startInfo.WorkingDirectory = localpath;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    output = exeProcess.StandardOutput.ReadToEnd();
                    exeProcess.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                output = ex.Message;
                // Log error.
                //Logger.Error($"Erro ao executar script {e.Message}");
            }
            File.AppendAllText(logPath, output + Environment.NewLine);
            try
            {
                var test = PowerShell.Create().AddScript("Get-LocalUser").Invoke();
                System.IO.File.AppendAllText(logPath, "test->" + test);
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }
            File.AppendAllText(logPath, output + Environment.NewLine);
        }
        protected override void OnStop()
        {

            File.AppendAllText(logPath, "stop->" + DateTime.Now.ToString("yyyyMMdd:HHmmss") + Environment.NewLine);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            
        }
    }
}
1

There are 1 best solutions below

1
pbianchi On

I think I solved the problem. After searching the web there're some ps commands you have to enable x64 in the solution. And the service was 'Any CPU'. After fixing to x64 it worked.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localuser?view=powershell-5.1

'The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit PowerShell on a 64-bit system.'