簡體   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