如何从C#程序向PowerShell脚本传递参数?

3

我有一个脚本文件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。这是否可行?
2个回答


0

与其读取文件并使用Commands.AddScript将其内容作为文本注入,我更愿意使用Commands.Add方法添加一个命令,以直接调用Sample.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-你可以向运行时环境注入一些初始变量,所以你可以使用它来将值传递给内联脚本。但是,这些值将已经是in-variables,而不是ARGV或类似的变量。

FYI:我还没有尝试过。我是基于这个问题来推测的。它应该可行,但仍然只是我的猜测。 - quetzalcoatl
我尝试了上述方法,但是没有参数,但是我收到以下错误:'Unhandled Exception: System.Management.Automation.RemoteException: The term 'C:\scripts\Sample.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.' - cmm user

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接