c# - .NET API 运行 powershell 脚本

标签 c# .net api rest powershell

<分区>

我不确定如何解决这个问题,我正在寻找使用 C#.NET 创建 REST API 的任何引用或提示,它将运行保存在 .PS1 文件中的 power shell 脚本并返回 Json 媒体类型。我对带有数据模型的 API 的经验有限。但由于这个没有模型,我迷路了。特别是对于对象的集合。我需要运行脚本并以 Json 格式返回 shell 输出。谢谢

最佳答案

您想从 C# 程序调用 powershell。 This MSDN link描述了这样做的方法。重要功能来自 System.Management.Automation 库。这是从那篇文章中复制的一些示例代码:

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
    PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
            "$d; $s; $param1; get-service");

    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
    PowerShellInstance.AddParameter("param1", "parameter 1 value!");

//在管道上调用执行(忽略输出) PowerShellInstance.Invoke();

阅读文章了解更多详情。

关于c# - .NET API 运行 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200661/

相关文章:

c# - 如何在 C# 中向类、方法、属性等添加文档工具提示?

c# - 在异步方法完成之前,UI 不会更新

c# - 使用带有动态匿名对象的 NHibernate 在 GroupBy 查询中进行选择

c# - 使用 C# 将图像上传到 Imgur.com

c# - 生成传出 url 时选择了意外的路由

c# - 如何更改 app.config 的位置

.net - Web.config 的最大大小是多少?

.net - 根据IP地址获取域名

jquery - 执行函数时使用 Apache Cordova 振动 (jQuery Mobile)

java - 使用 CriteriaQuery API 的多态 JPA 查询