PS: Call C Sharp Code

less than 1 minute read

Description:

From Microsoft, this is how you call C Sharp code into PS scripts:

To Resolve:

  1. Use the following template:

    1
    2
    3
    4
    5
    6
    7
    
    $Assem = (
    add referenced assemblies here
    )
    $Source = @"
    …add C# source code here…
    "@
    Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
    
  2. Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    $Assem = (
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ,
    "Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    )
    $Source = @"
    using Microsoft.SharePoint.Publishing.Administration;
    using System;
    namespace StefanG.Tools
    {
    public static class CDRemoteTimeout
    {
    public static void Get()
    {
    ContentDeploymentConfiguration cdconfig = ContentDeploymentConfiguration.GetInstance();
    Console.WriteLine("Remote Timeout: "+cdconfig.RemoteTimeout);
    }
    public static void Set(int seconds)
    {
    ContentDeploymentConfiguration cdconfig = ContentDeploymentConfiguration.GetInstance();
    cdconfig.RemoteTimeout = seconds;
    cdconfig.Update();
    }
    }
    }
    "@
    Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
    [StefanG.Tools.CDRemoteTimeout]::Get()
    [StefanG.Tools.CDRemoteTimeout]::Set(600)
    # The last lines in the above listed sample demonstrates how to call the C# methods from Powershell.
    

Comments