c# - 有没有办法在不使用 System.Management.Automation 的情况下捕获 powershell 脚本执行的输出

标签 c# asp.net powershell amazon-web-services

下面的方法启动一个powershell脚本并执行它

 private static void LaunchPowershell()
    {
        string exeDir = "H:\\aws-newAPIKey";

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = @"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe";
        startInfo.Arguments = exeDir + "\\newApiKey_wh1.ps1";
        startInfo.WorkingDirectory = exeDir;

        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();
    }

这会在命令行中产生以下输出:
CreatedDate     : 1/3/2018 7:20:16 PM
CustomerId      : 
Description     : This is api key for customer
Enabled         : True
Id              : qraj84yl5h
LastUpdatedDate : 1/3/2018 7:20:16 PM
Name            : newAPIKey7
StageKeys       : {}
Value           : 2LBtWluNX1XbgtDG0SPY1IQgnVDkZTwzmgY3kd60

我想要做的是获取在 C# 中创建的 API key 的值。有没有办法在不使用 System.Management.Autmomation 库的情况下做到这一点?

最佳答案

您的 PowerShell 管道运行 新ApiKey_wh1.ps1 可能会返回您显示的输出的脚本。

在不了解脚本的情况下,我不得不猜测,但您应该能够使用 Select-Object在脚本返回的输出上声明您想要的值。

因此,如果脚本执行以下操作:

return $Key

那你可以试试:
return ($Key | Select-Object -ExpandProperty Value)

这将只提取名为 的属性的值。值(value) .

关于c# - 有没有办法在不使用 System.Management.Automation 的情况下捕获 powershell 脚本执行的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48084608/

相关文章:

c# - 自动更新方法签名(例如摘要注释)

javascript - 在文本框中输入更改文本后执行回发

c# - 读取文件时出现 UnauthorizedAccessException

powershell - 在 PowerShell 中关闭所有资源管理器窗口

powershell - Powershell使用System.Windows.Forms.SaveFileDialog将目录位置选择为变量

c# - 对 UserControl 进行验证工作

c# - 使用 char 数组编码异常

c# - 使用 PowerShell 从 FTP 服务器删除文件

asp.net - 正则表达式-将文本追加到youtube链接的 'src'字段

function - 函数中的日志文件变量会占用所有内存