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:
    #Template:
$Assem = (
…add referenced assemblies here…
)
$Source = @”
…add C# source code here…
“@
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
  1. Example:
$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.