繁体   English   中英

从C#环境向Powershell脚本文件传递参数

[英]passing parameter to the powershell script file from C# environment

我知道主题行看起来太平凡了,有帖子解决了许多这样的问题。 我没有找到我真正想要的东西,因此没有这篇文章。

我正在从机器A调用Powershell文件,以在远程机器(机器B)上执行。

//这是代码段:

 Runspace runspace = RunspaceFactory.CreateRunspace();
 runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
string scripttext = "$secpasswd = ConvertTo-SecureString '222_bbbb' -AsPlainText –Force";
string scripttext1 = "$mycreds = New-object -typename System.Management.Automation.PSCredential('TS-TEST-09\\Administrator',$secpasswd)";
string scripttext2  = "$s = New-PSSession -ComputerName TS-TEST-09 -Credential $mycreds";
**string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' | out-null";**

pipeline.Commands.AddScript(scripttext);
pipeline.Commands.AddScript(scripttext1);
pipeline.Commands.AddScript(scripttext2);
pipeline.Commands.AddScript(scripttext5);

Collection<PSObject> results = pipeline.Invoke();

现在在行字符串scripttext5 =“ Invoke-Command -Session $ s -FilePath'helper.ps1'| out-null”; 我必须将一些参数(例如,来自c#环境的用户名:useralias)传递到此helper.ps1文件进行处理。 有人可以指导我采取正确的方法吗?

TIA,Manish

如果用户名和用户别名来自本地计算机,则可以这样做:

string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' -Args " + 
                      username + "," + useralias + " | Out-Null";

假定您的helper.ps1文件至少使用两个参数。 如果是这样,则C#变量usernameuseralias将分配给前两个参数。

好的,这是对我有用的解决方案。

它来自Keith解决方案。 诀窍是使用

runspace.SessionStateProxy.SetVariable("PSuseralias", this.useralias);

现在使用$ PSuseralias作为

string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' -Args  $PSuseralias;

这可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM