2

i understand that the subject line looks too mundane and there are posts addressing many such questions. I did not find what i was exactly looking for and hence this post.

I am invoking a powershell file from machine A to be executed on a remote machine(machine B).

//here is the code snippet:

 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();

now in line string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' | out-null"; i have to pass a few parameters(for example, username from c# environment : useralias) to this helper.ps1 file for processing. can any one guide me to a correct method of doing so?

TIA, Manish

user1156612
  • 41
  • 1
  • 3

2 Answers2

0

If the username and useralias come from the local machine then you can do so like this:

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

This assumes that your helper.ps1 file takes at least two parameters. If so, then the values of the C# variables username and useralias will get assigned to the first two parameters.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Hi Keith ..your assumptions are valid for the case ..but when i try for these two variables, user name is supplied as 'username' itself rather than the value contained in this parameter. i tried even after removing " " from -Args " + username + " but to no avail. can we rectify this behavior somehow? – user1156612 Jan 25 '12 at 09:49
  • That should work but if not, try this: `string scripttext5 = String.Format("Invoke-Command -Session $s -FilePath 'helper.ps1' -Args {0},{1} | Out-Null", username, useralias);` – Keith Hill Jan 25 '12 at 13:44
0

okay so here is the solution that worked for me.

it takes its bits from Keith's solution. the trick is to expose variables from c# using

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

now using $PSuseralias as

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

this does the trick.

animuson
  • 53,861
  • 28
  • 137
  • 147
user1156612
  • 41
  • 1
  • 3