An Overview of Windows PowerShell 1.0 and .NET

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Windows PowerShell 1.0 File HandlingCreating GUIs in Windows PowerShell 1.0 with WinForms

Purchase and download the full PDF version of this PowerShell eBook for only $8.99

Buy eBook

The power of Windows PowerShell is enhanced significantly by the ability to access and utilize the .NET framework from within both the shell environment and PowerShell scripts. This means that if there is a requirement for which a Windows PowerShell cmdlet or construct is not available, there is a very good chance the behavior is available via .NET. For example, Windows PowerShell is a text based environment with no built in support for creating and displaying graphical user interfaces (GUIs). Through the use of .NET WinForms support, however, even the most complex of GUIs can be created quickly and easily from with Windows PowerShell.

In this chapter of Windows PowerShell 1.0 Essentials the basics of using .NET within Windows PowerShell will be covered. In the next chapter, Creating GUIs in Windows PowerShell 1.0 with WinForms, will cover creation of graphical user interfaces.

The Basics of .NET

.NET is a vast framework of libraries (also referred to as assemblies) which provide application programming interfaces (APIs) designed to perform a wide range of application functions. For example, assemblies are provided specifically for graphical user interface creation, web application development, business process handling and database access (to name just a few). Microsoft has invested significant research and development into developing .NET to the extent that it is now one of the most comprehensive development frameworks available today.

Factor into this the fact that much of the power of .NET is available from within Windows PowerShell and the significance of this relationship quickly becomes evident.

Exploring .NET Assemblies in Windows PowerShell

As previously mentioned, the .NET functionality is provided via a collection of assemblies. These are essentially dynamic link libraries packaged into Windows .dll files. The majority of .NET assemblies are not loaded into Windows PowerShell by default, and must therefore, be loaded prior to being used. There are, however, a number of assemblies which are pre-loaded by default when Windows PowerShell is invoked. A full list of the currently loaded assemblies can be obtained using the following command:

PS C:\> [AppDomain]::CurrentDomain.GetAssemblies() | fl

The above command will output detailed information about each currently loaded .NET assembly. One such entry might appear as follows:

CodeBase               : file:///C:/Windows/assembly/GAC_MSIL/System.Configuration.Install/
EntryPoint             :
EscapedCodeBase        : file:///C:/Windows/assembly/GAC_MSIL/System.Configuration.Install/
FullName               : System.Configuration.Install, Version=, Culture=neutral, PublicKeyT
GlobalAssemblyCache    : True
HostContext            : 0
ImageFileMachine       :
ImageRuntimeVersion    : v2.0.50727
Location               : C:\Windows\assembly\GAC_MSIL\System.Configuration.Install\
ManifestModule         : System.Configuration.Install.dll
MetadataToken          :
PortableExecutableKind :
ReflectionOnly         : False

Specific values may be extracted using the select-object cmdlet. For example, to list just the FullName field:

PS C:\> [AppDomain]::CurrentDomain.GetAssemblies() | select-object FullName

mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft.PowerShell.ConsoleHost, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35
System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Management.Automation, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35
System.Configuration.Install, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Microsoft.PowerShell.Commands.Management, Version=, Culture=neutral, PublicKeyToken=31bf3...
Microsoft.PowerShell.Security, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Microsoft.PowerShell.Commands.Utility, Version=, Culture=neutral, PublicKeyToken=31bf3856...
System.Data, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Xml, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.DirectoryServices, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
System.Management, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

Loading .NET Assemblies into Windows PowerShell

If .NET functionality is required from an assembly which is not loaded by default when Windows PowerShell is invoked, it must first be loaded before it can be used. This is achieved using the LoadWithPartialName() static method of the [System.Reflection.Assembly] class. For example, to load the WinForms assembly in preparation for creating a GUI based application, the following would need to be executed:

PS C:\> [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\Windows\assembly\GAC_MSIL\System.Windows.Forms\

Once loaded, the classes in the assembly may subsequently be called upon to perform tasks from within Windows PowerShell.

.NET Static Members and Properties

Static methods and properties may be accessed without creating instances of the class in question. The syntax for accessing a static method is as follows:


For example, the following invokes the Get_BackgroundColor() static method of the [System.Console] class to obtain the background color of the Windows PowerShell console window:

PS C:\> [System.Console]::get_backgroundcolor()

Alternatively, the Set_BackgroundColor() method may be invoked to switch the background of the console to a different color:

PS C:\> [System.Console]::Set_backgroundcolor("red")

Similarly the static properties of a class may be accessed using the following syntax:


In the following example, the above syntax is used to extract today's date from the [System.DateTime] class:

PS C:\> [System.DateTime]::Today

Tuesday, December 09, 2008 12:00:00 AM

It is not typically possible to set the value of a static property.

Instance Members and Properties

In the case of instance members, an instance of the class must first be created before the methods and properties of that class may be used from within PowerShell. The syntax for creating an instance of a class (also referred to as an object) requires the use of the new-object cmdlet as illustrated below:

$object = new-object classname(parameters)

Once an instance has been created, methods may be accessed using the following syntax:


Similarly, instance properties may be accessed and set as follows:


$object.PropertyName = new_value

For example, to create an instance of the [System.Net.WebClient] class, and then call an instance method on that object:

PS C:\> $webobject = new-object System.Net.WebClient
PS C:\> $webobject.downloadstring("")

Listing the Methods and Properties of a .NET Class

The .NET Framework is a vast collection of classes, methods and properties. As such there are many resources both in print and on-line providing detailed .NET reference information. If all that is required, however, is a listing of the methods and properties available in a .NET class, this can be obtained from within the Windows PowerShell environment using the get-members cmdlet.

To obtain a list of all instance methods and properties of a particular class, simply pipe it through to the get-members cmdlet as illustrated below:

PS C:\> [System.DateTime] | get-member

   TypeName: System.RuntimeType

Name                           MemberType Definition
----                           ---------- ----------
Clone                          Method     System.Object Clone()
Equals                         Method     System.Boolean Equals(Object obj), System.Boolean Equa...
FindInterfaces                 Method     System.Type[] FindInterfaces(TypeFilter filter, Object...
FindMembers                    Method     System.Reflection.MemberInfo[] FindMembers(MemberTypes...
GetArrayRank                   Method     System.Int32 GetArrayRank()
GetConstructor                 Method     System.Reflection.ConstructorInfo GetConstructor(Bindi...
GetConstructors                Method     System.Reflection.ConstructorInfo[] GetConstructors(Bi...
GetCustomAttributes            Method     System.Object[] GetCustomAttributes(Boolean inherit), ...
GetDefaultMembers              Method     System.Reflection.MemberInfo[] GetDefaultMembers()
Assembly                       Property   System.Reflection.Assembly Assembly {get;}
AssemblyQualifiedName          Property   System.String AssemblyQualifiedName {get;}
Attributes                     Property   System.Reflection.TypeAttributes Attributes {get;}
BaseType                       Property   System.Type BaseType {get;}
ContainsGenericParameters      Property   System.Boolean ContainsGenericParameters {get;}
DeclaringMethod                Property   System.Reflection.MethodBase DeclaringMethod {get;}
DeclaringType                  Property   System.Type DeclaringType {get;}
FullName                       Property   System.String FullName {get;}
GenericParameterAttributes     Property   System.Reflection.GenericParameterAttributes GenericPa...
GenericParameterPosition       Property   System.Int32 GenericParameterPosition {get;}

Similarly, a listing of the static methods and properties of a .NET class may be obtained using the -static option of the get-members cmdlet:

PS C:\> [System.DateTime] | get-member -static

   TypeName: System.DateTime

Name                  MemberType Definition
----                  ---------- ----------
Compare               Method     static System.Int32 Compare(DateTime t1, DateTime t2)
DaysInMonth           Method     static System.Int32 DaysInMonth(Int32 year, Int32 month)
Equals                Method     static System.Boolean Equals(DateTime t1, DateTime t2), static ...
FromBinary            Method     static System.DateTime FromBinary(Int64 dateData)
FromFileTime          Method     static System.DateTime FromFileTime(Int64 fileTime)
FromFileTimeUtc       Method     static System.DateTime FromFileTimeUtc(Int64 fileTime)
FromOADate            Method     static System.DateTime FromOADate(Double d)
get_Now               Method     static System.DateTime get_Now()
get_Today             Method     static System.DateTime get_Today()
get_UtcNow            Method     static System.DateTime get_UtcNow()
IsLeapYear            Method     static System.Boolean IsLeapYear(Int32 year)
MaxValue              Property   static System.DateTime MaxValue {get;set;}
MinValue              Property   static System.DateTime MinValue {get;set;}
Now                   Property   System.DateTime Now {get;}
Today                 Property   System.DateTime Today {get;}
UtcNow                Property   System.DateTime UtcNow {get;}