【问题标题】:How to pass arguments to a powershell script from C# program?如何从 C# 程序将参数传递给 powershell 脚本?
【发布时间】:2014-01-07 18:41:36
【问题描述】:

我有一个脚本文件 sample.ps1,其中包含以下命令:

copy-item C:\source -destination C:\destination.

我不想硬编码源和目标的值,而是将其作为参数传递给脚本。

copy-item $source -destination $destination.

我想从独立客户端调用此脚本并将源和目标作为参数传递。 我有以下程序来执行脚本文件:

            string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            string userName = "MachineName\\Administrator";
            string password = "Password";
            SecureString securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            PSCredential credential = new PSCredential(userName, securePassword);
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {

                runspace.Open();
        String file = "C:\\scripts\\Sample.ps1";
                Pipeline pipeline = runspace.CreatePipeline();

                pipeline.Commands.AddScript(System.IO.File.ReadAllText(file));
        }

我想通过C#程序将参数传递给脚本Sample.ps1。这怎么可能?

【问题讨论】:

    标签: c# powershell parameter-passing


    【解决方案1】:

    与其读取文件并使用Commands.AddScript 将其内容注入作为文本,我更愿意使用Commands.Add 方法添加一个将调用示例的命令。 ps1 脚本直接作为文件:

    pipeline.Commands.Add( "C:\\dirWithNoSpaces\\scripts\\Sample.ps1 -param1 value1");
    

    但要小心转义.. 我刚刚读到如果路径中有任何空格,则必须引用它:

    pipeline.Commands.Add( "&\"C:\\dir with spaces\\scripts\\Sample.ps1\" -param1 value1");
    

    但是,如果您想保持现有状态,您可能会寻找一些方法在 Pipeline 或 Runspace 对象中添加“参数”。例如,我刚刚发现:Runspace.InitialSessionState - 您将一些初始变量注入运行时环境,因此您可以使用它将值传递给内联脚本。但是,这些值已经是不变量,而不是 ARGV 等。

    【讨论】:

    • 仅供参考:我还没有尝试过。我基于this question。它应该可以工作,但我仍然只是猜测。
    • 我在没有参数的情况下尝试了上述方法,但出现以下错误:'Unhandled Exception: System.Management.Automation.RemoteException: The term 'C:\scripts\Sample.ps1' is not识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。'
    【解决方案2】:
    猜你喜欢
    • 2015-06-07
    • 2012-05-05
    • 1970-01-01
    • 2020-11-19
    • 2021-08-26
    • 2011-08-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多