简体   繁体   中英

passing parameter to the powershell script file from C# environment

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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