2012-01-24 68 views
2

我明白主题行看起来很平常,并且有帖子可以解决很多这样的问题。我没有找到我正在寻找什么,因此这篇文章。将参数传递给C#环境中的powershell脚本文件

我从机器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 = “调用命令-Session $ S -FilePath 'helper.ps1' |外空”; 我必须传递一些参数(例如,来自c#environment:useralias的用户名)到这个helper.ps1文件进行处理。任何人都可以指导我采取正确的方法吗?

TIA, 马尼什

+0

任何有关完整源代码的最终解决方案? – Kiquenet

回答

0

如果用户名和USERALIAS来自本地机器,那么你可以这样做是这样的:

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

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

+0

嗨基思..你的假设是有效的案件..但是当我尝试这两个变量,用户名是作为'用户名'本身提供,而不是包含在此参数中的值。我甚至在从“Args”+用户名+“中删除”“后尝试,但无济于事。我们能否以某种方式纠正这种行为? – user1156612

+0

这应该工作,但如果没有,试试这个:'string scripttext5 = String.Format(“Invoke-Command -Session $ s -FilePath'helper.ps1'-Args {0},{1} | Out-Null”,username ,useralias);' –

0

没关系,所以这里是适合我的解决方案。

它从Keith的解决方案中获取它的位。诀窍是使用

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

现在用$ PSuseralias揭露从C#变量

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

这样做的伎俩。

相关问题