我有一个脚本文件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。怎么可能?
答案 0 :(得分:1)
以下是您的问题的答案:
答案 1 :(得分: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 - 您将一些初始变量注入运行时环境,因此您可以使用它将值传递给内联脚本。但是,这些值已经是变量,而不是ARGV等。