簡體   English   中英

如何通過New-Variable將數組變量注入PowerShell Runspace

[英]How to Inject an Array Variable into a PowerShell Runspace via New-Variable

假設我已創建並打開了運行空間

            var rs = RunspaceFactory.CreateRunspace();
            rs.Open();

讓我們進一步假設我想通過使用New-Variable cmdlet將變量添加到作為數組類型的運行空間中,如下所示:

            // create a pipeline to add the variable into the runspace
            var pipeline = PowerShell.Create();
            // create a command object, add commands and parameters to it...
            var cmd = new PSCommand();
            cmd.AddCommand("New-Variable");
            cmd.AddParameter("Name", "foo");
            cmd.AddParameter("Value", "@()");
            // associate the command with the pipeline and runspace, and then invoke
            pipeline.Commands = cmd;
            pipeline.Runspace = rs;
            pipeline.Invoke();

代碼工作,我沒有錯誤,但變量'foo'不是作為數組類型創建的。 我在“@()”上嘗試了很多不同的變體,但到目前為止它們都沒有被淘汰。 最后,我認為問題歸結為如何將Value參數正確格式化為New-Variable,以便'foo'將被解釋為空的PowerShell數組類型。

謝謝,

馬特

僅供參考,你可以直接在C#中這樣做:

pipeline.Runspace.SessionStateProxy.PSVariable.Set("foo", new object[0]);

拯救我的回應是:

如果您是從文本中完成所有操作,則可以查看AddScript方法。 例如, var cmd = new PSCommand().AddScript("$myVar = @()"); 將生成一個名為$myVar的新變量。

C#代碼示例:

foreach (Collaborator collab in collabs)
                {
                    counter ++;
                    arrayUsers.Append("@(\"" + collab.mail + "\", \"" + collab.url + "\")");
                    if (counter < numbercollabs)
                        arrayUsers.Append(",");
                }
                string arrayUsersPowerShell =  arrayUsers.ToString();
and then :

using (PowerShell powerShellInstance = PowerShell.Create())
                {
 powerShellInstance.AddScript("$d = get-date; " +
                        "$arrayUsers = @(" + arrayUsersPowerShell + "); " +
                        "$d | Out-String; $arrayUsers[0][1]");
...
Collection<PSObject> PSOutput = powerShellInstance.Invoke();
...
}

所以我們可以正確構造數組

PSCommand.AddParameter獲取參數名稱的字符串,以及參數值的對象 請參閱此處的文檔。

你應該放一個“真正的”空數組,而不是代表powershell腳本等價的字符串。

cmd.AddParameter("Value", new object[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM