To PowerShell From C#

# powershell
// csharp

Part 1: Language

Values, Types, and Operators

42
0x2a
[char]'*'
'hello world`n'
"hello $name`r`n"
3 + 5 -eq 8 -and $True
42 -is [int]
[xml]"<a>42</a>" # feature
1 / 0 # error
5 / 3
@(1,2,3) # @() can be omitted
@{a=1;b=2}
{ whatever } # script block
42
0x2a
'*'
@"hello world`n"
$"hello {name}\r\n"
3 + 5 == 8 && true
42 is int
XmlDocument...LoadXml...
1 / 0 // error
(double)5 / 3
new [] { 1, 2, 3 }
new Hashtable { {"a",1}, {"b",2} }
() => { whatever; }

Arrays with only one element will be flattened to that element. To always get an array, use @(whatever).

Program Structure

[int]$a = 42
if ($a -gt 0) {
  $a--
} elseif ($a -lt 0) {
  ++$a
} else {
  "got zero"
}
while ($a -neq 0) { $a = 0 }
do { "hello" } while ($False)
using namespace System.IO
try {
  [int].TryParse([File]::OpenText('a.txt').ReadLine(), [ref]$a)
} catch [FileNotFoundException] {
  "not found"
} finally {
  "done"
}
int a = 42;
if (a > 0) {
  a--;
} else if (a < 0) {
  ++a;
} else {
  "got zero";
}
while (a != 0) { a = 0; }
do { "hello"; } while (false);
using System.IO;
try {
  int.TryParse(File.OpenText("a.txt").ReadLine(), out a);
} catch (FileNotFoundException) {
  "not found";
} finally {
  "done";
}

Switch statement works quite differently from C#.

Functions

function f { 42 }
f #=> 42 (last expression returns)
function f($a, $b) { $a * $b }
f 6 7 #=> 42
# f(6, 7) === f @(6,7) $Null
function f([Parameter(Mandatory=$true)][int]$a, $b = 2) { $a * $b }
help f
.... f [-a] <int> [[-b] <Object>]  [<CommonParameters>]

Part 2: .NET

(42).GetType()
[System.Console]::WriteLine(1)
[Random]::new().Next()
class A {
  [int]$i
  A ([int]$i) {
    $this.i = $i
  }
  static [int]op_Addition([A]$a, [int]$j) {
    return $a.i + $j
  }
}
[A]::new(3) + 5
42.GetType();
System.Console.WriteLine(1);
new Random().Next();
public class A {
  public int i;
  public A (int i) {
    this.i = i;
  }
  public static int operator +(A a, int j) {
    return a.i + j;
  }
}
new A(3) + 5;
[A]::new(1) | Get-Member
Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()
i           Property   int i {get;set;}
[A] | Get-Member -Static
Name            MemberType Definition
----            ---------- ----------
Equals          Method     static bool Equals(System.Object objA, System.Object objB)
new             Method     A new(int i)
op_Addition     Method     static int op_Addition(A a, int j)
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object objB)

Misc

© 2019 hyrious