Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expression in Powershell

I have a code in C# which uses lambda expressions for delegate passing to a method. How can I achieve this in PowerShell. For example the following is a C# code:

string input = "(,)(;)(:)(!)"; string pattern = @"\((?<val>[\,\!\;\:])\)"; var r = new Regex(pattern); string result = r.Replace(input, m =>     {         if (m.Groups["val"].Value == ";") return "[1]";         else return "[0]";     }); Console.WriteLine(result); 

And this is the PowerShell script without the lambda-expression in place:

$input = "(,)(;)(:)(!)"; $pattern = "\((?<val>[\,\!\;\:])\)"; $r = New-Object System.Text.RegularExpressions.Regex $pattern $result = $r.Replace($input, "WHAT HERE?") Write-Host $result 

Note: my question is not about solving this regular-expression problem. I just want to know how to pass a lambda expression to a method that receives delegates in PowerShell.

like image 767
Sina Iravanian Avatar asked Jun 12 '12 11:06

Sina Iravanian


People also ask

Can you use PowerShell with lambda?

You can also now view PowerShell code in the AWS Management Console, and have more control over function output and logging. Lambda has supported running PowerShell since 2018.

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.

How do you create a function in PowerShell?

To define a function, you use the function keyword, followed by a descriptive, user-defined name, followed by a set of curly braces. Inside the curly braces is a scriptblock that you want PowerShell to execute. Below you can see a basic function and executing that function.

What is auto lambda expression?

Immediately invoked lambda expression is a lambda expression which is immediately invoked as soon as it is defined. For example, #include<iostream> using namespace std; int main(){ int num1 = 1; int num2 = 2; // invoked as soon as it is defined auto sum = [] (int a, int b) { return a + b; } (num1, num2);


2 Answers

In PowerShell 2.0 you can use a script block ({ some code here }) as delegate:

$MatchEvaluator =  {     param($m)     if ($m.Groups["val"].Value -eq ";")    {      #...    } }  $result = $r.Replace($input, $MatchEvaluator) 

Or directly in the method call:

$result = $r.Replace($input, { param ($m) bla }) 

Tip:

You can use [regex] to convert a string to a regular expression:

$r = [regex]"\((?<val>[\,\!\;\:])\)" $r.Matches(...) 
like image 141
Stefan Avatar answered Sep 19 '22 18:09

Stefan


Sometimes you just want something like this:

{$args[0]*2}.invoke(21) 

(which will declare an anonymous 'function' and call it immediately.)

like image 29
Randall Bohn Avatar answered Sep 19 '22 18:09

Randall Bohn