1

The below method launches a powershell script and executes it

 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();
    }

This results in the following output in the command line:

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

What I want to do is to obtain the Value of the API key created in C#. Is there a way to do this without using System.Management.Autmomation library?

the_coder_in_me
  • 143
  • 3
  • 15

2 Answers2

2

Your PowerShell pipeline runs the newApiKey_wh1.ps1 script which presumably returns the output you have shown.

Without knowing more about the script I'll have to guess, but you should be able to use the Select-Object statement on the output that is returned by the script to just the value you want.

So, if the script does something like:

return $Key

Then you could try:

return ($Key | Select-Object -ExpandProperty Value)

This will pull out just the value of the property named Value.

Charlie Joynt
  • 4,411
  • 1
  • 24
  • 46
1

If you want to retrieve complex data from powershell by executing a process, then you could use ConvertTo-Json on the powershell object, and parse it in C#

Although it looks like you're trying to create an API key for AWS, so why not just use the AWS SDK for .NET?

Jess
  • 352
  • 1
  • 2
  • 10
  • The proper way to do it is by using AWS SDK process.StartInfo.RedirectStandardOutput = true; process.Start(); while (!process.StandardOutput.EndOfStream) { string line = process.StandardOutput.ReadLine(); Console.WriteLine(line); // do something with line } Parse it to get whichever value you require.. This is the solution that I used without using the powershell class – the_coder_in_me Jan 03 '18 at 20:50