簡體   English   中英

從 C# 控制台應用程序中的 Powershell 腳本讀取 json 數據

[英]Read json data from Powershell script in c# console application

我正在嘗試閱讀 PowerShell 腳本以在 Azure 中創建機器人服務。 我能夠在 Windows PowerShell 中實現這一點,但是當我嘗試從控制台應用程序讀取相同的腳本時,它不返回任何內容。 我的目的是將此腳本作為 webjob 運行。 下面是我的 C# 代碼

  using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
            {
                myRunSpace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    // Create a pipeline with the Get-Command command.
                    powershell.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
                    powershell.AddScript(@"C:\Users\Admin\Desktop\MyFile.ps1");
                    // add an extra command to transform the script output objects into nicely formatted strings
                    // remove this line to get the actual objects
                    powershell.AddCommand("Out-String");
                    // execute the script
                    var results = powershell.Invoke();
                    powershell.Streams.ClearStreams();
                    powershell.Commands.Clear();
                    // convert the script result into a single string
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in results)
                    {
                        stringBuilder.AppendLine(obj.ToString());
                    }
                    Console.WriteLine(stringBuilder.ToString());
                    Console.ReadLine();
                }
            }

這是我的腳本:

Connect-AzureRmAccount;
$Name="Hello";
$Password="xxxx";
$desc=az ad app create --display-name $Name --password $Password --available-to-other-tenants;
return $desc;

此腳本在 windows powershell 中的變量“$desc”中返回 Json,但不在控制台應用程序中。 如果缺少任何東西,任何人都可以在這里幫助我。

您似乎在執行命令后清除流,因此它會刷新結果。

// execute the script
var results = powershell.Invoke();
// Clears all the Streams 
powershell.Streams.ClearStreams();

嘗試在調用之前清除流

// Clears all the Streams 
powershell.Streams.ClearStreams();
// execute the script
var results = powershell.Invoke();

基於上面的討論,我想給出一個更完整的答案,知道我們更了解場景。

對於您嘗試執行的操作,您基本上希望從 C#(在本例中為 Azure 中的 Web 作業)連接 Azure 后端服務以提供某些內容。 我建議,現在,有太多的技術阻礙了你。 基本上是(現在):Azure Webjob -> PowerShell -> Azure Cli ("az) -> Azure SDK -> Azure API(或 Graph API)

相反,我建議您執行以下操作之一:

1) 考慮到您使用的是 C#,您可以直接調用 Microsoft Graph API,跳過混合中的 3 種技術。 例如,要創建 Azure AD 應用程序,您需要調用創建應用程序終結點。 幸運的是,您甚至不需要直接調用端點,您可以使用Microsoft 提供的 .net(即 C#) SDK來完成此類操作。

2)除此之外,出於興趣,您為什么要使用網絡作業? 我建議您改用Azure Functions - 它們非常適合輕量級(並且可能更便宜,具體取決於您要做什么)

3) 除了上述之外,還有完全不同的方式來部署和管理 Azure 工件(應用程序、機器人等)。 您應該將Azure 資源管理器作為一種選擇,或者在“基礎設施即代碼”類型的解決方案中使用類似Terraform的方法。

所以一些家庭作業可能適合你,但希望能有所幫助

暫無
暫無

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

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