Geeks With Blogs
Technically Speaking .NET Bloggers Sharing Ideas

I think there's nothing more powerful for a .NET developer than the ability to call into the .NET framework from script code.  Here are a couple of tips for calling into the framework from PowerShell 1.0:

For non-static .NET classes, use the New-Object commandlet (example using the SecureString class)

In c#

System.Security.SecureString password = new SecureString();

In PowerShell:

[System.Security.SecureString]$password = New-Object System.Security.SecureString

You don't have to explicitly cast the $password variable as a System.Security.SecureString type, but it helps to clearly state intent like this.

For calling methods of static .NET classes or structures, use the bracket []:: syntax (example using the GUID structure)

In c#

Guid guidVal = Guid.NewGuid();

In PowerShell:

[System.Guid]$guidVal = [Guid]::NewGuid()

To load an assembly that is not part of the .NET framework, but has been moved to the GAC (example using the Microsoft.SharePoint assembly)

In c#

In Visual Studio, add a reference to the assembly via the References folder and add a using statement:

using Microsoft.SharePoint;

In PowerShell:

$sharePointCore = New-Object System.Reflection.AssemblyName("Microsoft.SharePoint, Version=12.0.0.0, Culture=Neutral, PublicKeyToken=71e9bce111e9429c")

# then load this assembly since is not part of the OOB .NET Framework[Reflection.Assembly]::Load($sharePointCore)

Note that there are a number of ways to achieve this result. However, the method LoadWithPartialName in the Reflection.Assembly class is now obsolete. You'll see a number of PowerShell examples using this method. For example:

[Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

The Load method of the same class is a better choice since it's more explicit about the assembly you intend on loading and it's not obsolete.

I'll keep editing this entry as other interesting interactions with the .NET framework come up.

 TechnicallySpeaking author, Ethan Wilansky

Posted on Tuesday, October 28, 2008 6:13 PM SharePoint_Dev , Powershell | Back to top


Comments on this post: .NET and PowerShell

# re: .NET and PowerShell
Requesting Gravatar...
Calling the Load method to load an assembly that’s not part of the .NET framework will produce output similar to the following:

GAC Version Location
--- ------- --------
True v2.0.50727 C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SharePoint\12.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.dll

To suppress the output, add [Void] to the beginning of the command, for example:

[Void][Reflection.Assembly]::Load($sharePointCore)
Left by stefan kowalewski on Jan 06, 2009 1:22 PM

# re: .NET and PowerShell
Requesting Gravatar...
How to call a overloaded function in assembly from powershell?
Left by Ravi on Jul 16, 2009 2:02 PM

Your comment:
 (will show your gravatar)


Copyright © TechnicallySpeaking | Powered by: GeeksWithBlogs.net