首页 > 解决方案 > 无法运行 PS 脚本 - 未指定任何命令

问题描述

我目前正在尝试通过我的 C# 代码远程调用 PowerShell 脚本,但不知何故,我一直未能实现我的目标,而且我的谷歌搜索到目前为止没有成功。

我尝试将每个参数添加为“command.AddParameter”并使用“.AddParameter”,但我仍然遇到同样的问题,而且我的想法已经不多了。

                    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});

错误消息:( “vid”是瑞典语中“at”的意思,不知道为什么我的调试器会翻译我的部分错误消息,因为我用英文运行 VS)

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)

任何关于我做错了什么的想法将不胜感激!旁注:我宁愿不使用外部 PS 文件,但如果找不到解决方案,我可能会被迫使用。

编辑:用于澄清的整个功能。目前我只是在记录 PSOutputs 以查看发生了什么。

     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());
        }
    }

标签: c#.netpowershellvariablesinvoke-command

解决方案


正如 PetSerAI 在评论中指出的那样,我忘记将命令与实例本身挂钩。添加最后一行代码后,它似乎正在工作(仍然有访问错误,但这是我应该能够弄清楚的)。:)

                    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;

推荐阅读