Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Thursday, December 8, 2016

Powershell functions

I needed a simple .NET application with less than 10 lines of code... after writing the code in less than 2 minutes I thought about the maintenance, deployment, version control and so on...

Finally I decided to change the c# code into powershell and was surprised how easy it was to call .NET functions and how hard it was to work with functions... (this is a different example but with better param-handling and with about the same complexity).


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function CountOfDaysSince
{
    param(  [Parameter(Mandatory=$True ,Position=0)] [DateTime] $date,
            [Parameter(Mandatory=$False           )] [bool    ] $logging = $false);
    
    
    [int] $delta = ([System.DateTime]::Now.Subtract($date)).TotalDays;

    if($logging) {
        "Date is            : " + $date.ToShortDateString() | Write-host ;
        "Diff in Days to now: " + $delta                    | Write-host ;
    }

    return $delta
}

$x=CountOfDaysSince (New-Object System.DateTime(2012,08,04)) -logging $false
[int] $count = $x[-1]
Write-Host $count

For me functions are quite complex because I am not used to the syntax or the way how powershell functions are used. Even the naming is not very powershell-ish (Probably Count-DaysSince?). Writing return $delta returns $delta, but in fact the return type is object[]. I read on stackoverflow that return $a is equivalent to "$a; return;" what opens up the possibility to easily return 2 return values like "$a; $b; return". This is quite similar to stored procedures in SQL Server where a stored procedure can return multiple record sets. Nice, but not very intuitive. Thats the reason why line 18 gets one array item. With index -1 you will receive the last element of the array, which is also nice, but... :-)

kr,
Daniel

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