[英]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.