1.14.6. fejezet, PowerShell hívás

A mintaprogram lekérdezi a háttértárak adatait (betüjel, méret, szabad hely, stb.), majd Json formában adja azt vissza a c# hívásnak

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
 
namespace Homework4MultiPowershellCalls
{
    class Program
    {
 
        static void Main(string[] args)
        {
            PowerShell ps = PowerShell.Create();
            ps.AddScript("Set-ExecutionPolicy Unrestricted -Scope CurrentUser\r\n" +
                "Import-Module -name Storage\r\n" +
                "Get-Volume|Select -Property Driveletter,DriveType,FileSystem,size,SizeRemaining,UniqueId,path|ConvertTo-Json -compress");
            ps.Streams.Progress.DataAdded += myProgressEventHandler;
            ps.Streams.Error.DataAdded += myErrorEventHandler;
            Collection<PSObject> PSOutput = ps.Invoke();
            foreach(PSObject p in PSOutput)
            {
                string strJson = p.ToString();
                JArray jsonArray = JArray.Parse(strJson);
                for (int i = 0; i < jsonArray.Count; i++) {
                    JObject jsonObj = JObject.Parse(jsonArray[i].ToString());
                    JToken driveLetter = jsonObj["Driveletter"];
 
                    if (!IsNullOrEmpty(driveLetter))
                    {
                        jsonObj["sizeInGiB"] = (((long)jsonObj["size"]) / 1024L / 1024L / 1024L) + " GiB";
                        jsonObj["SizeRemainingInGiB"] = (((long)jsonObj["SizeRemaining"]) / 1024L / 1024L / 1024L) + " GiB";
                        Console.WriteLine(jsonObj.ToString());
                    }
                }
            }
            ps.Dispose();
        }
        static bool IsNullOrEmpty(JToken token)
        {
            return (token == null) ||
                   (token.Type == JTokenType.Array && !token.HasValues) ||
                   (token.Type == JTokenType.Object && !token.HasValues) ||
                   (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
                   (token.Type == JTokenType.Null);
        }
 
        static void myProgressEventHandler(object sender, DataAddedEventArgs e)
        {
            ProgressRecord newRecord = ((PSDataCollection<ProgressRecord>)sender)[e.Index];
            if (newRecord.PercentComplete != -1)
            {
                Console.Clear();
                Console.WriteLine("Progress updated: {0}", newRecord.PercentComplete);
            }
        }
        static void myErrorEventHandler(object sender, DataAddedEventArgs e)
        {
            ErrorRecord newRecord = ((PSDataCollection<ErrorRecord>)sender)[e.Index];
            String msg = newRecord.Exception.Message;
            {
                Console.Clear();
                Console.WriteLine("Exception message: {0}", msg);
            }
        }
    }
}