我有下一段代码可以调用远程 powershell 脚本(脚本进入远程系统),但我想将参数发送到脚本:
C# 方法:
public void RemoteConnection()
{
connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(path);
var results = pipeline.Invoke();
foreach (PSObject obj in results)
Console.WriteLine(obj.ToString());
}
我尝试使用 CommandParameter 发送参数,但收到一条错误消息:
Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command(path);
CommandParameter testParam0 = new CommandParameter("suma");
myCommand.Parameters.Add(testParam0);
CommandParameter testParam = new CommandParameter("x", "89");
myCommand.Parameters.Add(testParam);
CommandParameter testParam2 = new CommandParameter("y", "11");
myCommand.Parameters.Add(testParam2);
pipeline.Commands.Add(myCommand);
错误信息:
{"Cannot perform operation because operation \"NewNotImplementedException at offset 76 in file:line:column <filename unknown>:0:0\r\n\" is not implemented."}
我可以这样调用我的 powershell 脚本(它在我的远程系统中):
PS C:\grace\powershell> .\script1.ps1 -suma -x 9 -y 19
28
PS C:\grace\powershell> .\script1.ps1 -suma "9" "19"
28
如何为我的 powershell 脚本发送 c# 程序参数?
最佳答案
它是如何为我工作的:
public void RemoteConnection()
{
connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(path);
Command myCommand = new Command(path);
CommandParameter testParam0 = new CommandParameter("-suma");
myCommand.Parameters.Add(testParam0);
CommandParameter testParam = new CommandParameter("x", "34");
myCommand.Parameters.Add(testParam);
CommandParameter testParam2 = new CommandParameter("y", "11");
myCommand.Parameters.Add(testParam2);
pipeline.Commands.Add(myCommand);
var results = pipeline.Invoke();
foreach (PSObject obj in results)
Console.WriteLine(obj.ToString());
}
请注意,我正在将路径发送到 CreatePipeline 并创建一个新命令(可能需要进一步审查)
关于c# - 使用 c# 程序的参数调用远程 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25531984/