Search code examples
c#.netpowershellvariablesinvoke-command

Could not run PS-script - No commands are specified


I'm currently trying to remotely invoke a PowerShell script via my C# code but somehow I´m constantly failing to achieve my goal and my Google searches have so far turned up unsuccessful.

I have tried adding each parameter as "command.AddParameter" and by using ".AddParameter" but I'm still getting the same problem and I´m running out of ideas.

                    PSCredential credential = new PSCredential(LSUUser, password);
                    var command = new PSCommand();
                    command.AddCommand("Invoke-Command")
                    .AddParameter("ComputerName", computerName)
                    .AddParameter("Credential", credential)
                    .AddParameter("ScriptBlock", ScriptBlock.Create(@"param(${process}) Stop-Process ${process}"))
                    .AddParameter("Argumentlist", new object[] { process });

                    //Tried this as well, but no success :( 
                    //command.AddParameter("Scriptblock", ScriptBlock.Create(@"param($comp, $cred, $pro) -Computername $comp -Credential $cred Stop-Process $pro"));
                    //command.AddParameter("ArgumentList", new object[] {computerName, credential, process});

The error-message: ("vid" is the swedish word for "at", no idea why my debugger translates parts of my error messages since I run VS in English)

Could not run PS-script: System.Management.Automation.PSInvalidOperationException: No commands are specified.
    at System.Management.Automation.PowerShell.Prepare[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings, Boolean shouldCreateWorker)
    at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
    at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
    at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable input, PSDataCollection`1 output, PSInvocationSettings settings)
    at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings)
    at System.Management.Automation.PowerShell.Invoke()
    at <projectname>.TerminateProcess(String computerName, String process)

Any ideas to what I´m doing wrong would be greatly appreciated! Sidenote: I would rather not use an external PS-file but I may be forced to if no solution is found.

Edit: Whole function for clarification. Currently i´m just logging the PSOutputs to see what´s going on.

     public void TerminateProcess(string computerName, string process)
    {
        SecureString password = new SecureString();
        foreach(char c in LSUPass)
        {
            password.AppendChar(c);
        }

        try
        {
            //using (Runspace runspace = RunspaceFactory.CreateRunspace())
            //{
                using (PowerShell powerShellInstance = PowerShell.Create())
                {
                    PSCredential credential = new PSCredential(LSUUser, password);
                ScriptBlock scriptBlock = ScriptBlock.Create(@"param(${process}) Stop-Process ${process}");
                    var command = new PSCommand();
                command.AddCommand("invoke-command");
                    command.AddParameter("ComputerName", computerName);
                    command.AddParameter("Credential", credential);
                    command.AddParameter("ScriptBlock", scriptBlock);
                    command.AddParameter("Argumentlist", new object[] { process });

                    //Tried this as well, but no success :( 
                    //command.AddParameter("Scriptblock", ScriptBlock.Create(@"param($comp, $cred, $pro) -Computername $comp -Credential $cred Stop-Process $pro"));
                    //command.AddParameter("ArgumentList", new object[] {computerName, credential, process});
                    string PSDebug = "";
                    foreach(object com in command.Commands)
                    {

                        PSDebug = PSDebug + com.ToString();
                    }
                    Logger("INFO", PSDebug);


                    Collection<PSObject> PSOutput = powerShellInstance.Invoke();
                    if (powerShellInstance.Streams.Error.Count > 0)
                    {
                        foreach(ErrorRecord error in powerShellInstance.Streams.Error)
                        {
                            Logger("ERROR", error.ToString());
                        }
                    }
                    foreach (PSObject outputItem in PSOutput)
                    {
                        if (outputItem != null)
                        {
                            Logger("INFO", outputItem.BaseObject.GetType().FullName);
                        }
                    }
                }
            //}

        }
        catch (Exception e)
        {

            Logger("ERROR", "Could not run PS-script: " + e.ToString());
        }
    }

Solution

  • As PetSerAI pointed out in the comments, I had forgot to hook the command to the instance itself. After adding the last line of code it seems to be working (well still got access errors but that´s something I should be able to figure out). :)

                        PSCredential credential = new PSCredential(LSUUser, password);
                    ScriptBlock scriptBlock = ScriptBlock.Create(@"param(${process}) Stop-Process ${process}");
                        var command = new PSCommand();
                    command.AddCommand("invoke-command");
                        command.AddParameter("ComputerName", computerName);
                        command.AddParameter("Credential", credential);
                        command.AddParameter("ScriptBlock", scriptBlock);
                        command.AddParameter("Argumentlist", new object[] { process });
    
                    powerShellInstance.Commands = command;