2

我知道主题行看起来太普通了,并且有一些帖子解决了许多此类问题。我没有找到我正在寻找的东西,因此没有找到这篇文章。

我正在从机器 A 调用要在远程机器(机器 B)上执行的 powershell 文件。

//这里是代码片段:

 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,马尼什

4

2 回答 2

0

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

字符串 scripttext5 = "调用命令 -Session $s -FilePath 'helper.ps1' -Args " +
                      用户名 + "," + 用户别名 + " | Out-Null";

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

于 2012-01-24T17:59:27.050 回答
0

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

它从 Keith 的解决方案中汲取灵感。诀窍是使用 c# 公开变量

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

现在使用 $PSuseralias 作为

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

这可以解决问题。

于 2012-01-25T14:07:12.207 回答