Blog Stats
  • Posts - 7
  • Articles - 0
  • Comments - 7
  • Trackbacks - 0

 

.NET and PowerShell

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


Feedback

# re: .NET and PowerShell

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) 1/6/2009 1:22 PM | stefan kowalewski

# re: .NET and PowerShell

Gravatar How to call a overloaded function in assembly from powershell? 7/16/2009 2:02 PM | Ravi

Post a comment





 

 

 

 

Copyright © TechnicallySpeaking