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

No comments: