Tuesday, November 29, 2016

Powershell-code inside of my application

Hi,

I wanted to combine powershell and my .net application. In fact this works quite easily. The following link was quite helpful to make this work: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

We see here that an assembly has to be added (System.Management.Automation), but that's more or less it... I encapsulated the invocation of the powershell code into the following class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System.Management.Automation;
using System.Collections.ObjectModel;

class PSExecutor
{
    protected Collection<PSObject> Execute(string command, params Tuple<string, object>[] parameters)
    {
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            // add a script that creates a new instance of an object from the caller's namespace
            PowerShellInstance.AddScript(command);
            parameters.ToList().ForEach(x => PowerShellInstance.AddParameter(x.Item1, x.Item2));

            return PowerShellInstance.Invoke();
        }
    }
}

... so we can use this class as a base class (if you want to call the execution of the code directly: change method Execute to be public). The following snippet is an example how to use the base class:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    // https://gallery.technet.microsoft.com/Get-WindowsUpdatesps1-7c82c1f4
    class GetWindowsUpdatePSExecutor : PSExecutor
    {
        public Collection<PSObject> Execute()
        {
            return base.Execute(
@"
$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search(""IsInstalled=0"") # ""IsInstalled=0 and Type='Software' and IsHidden=0""
$SearchResult.Updates |Select-Object -Property Title, Description, SupportUrl, UninstallationNotes, RebootRequired
");
        }
    }

... with the snippet above you can check the OS for pending windows updates.

kr,
Daniel