Chapter 19. Inline .NET code

 

Richard Siddaway

PowerShell is .NET-based. This enables you to use the .NET framework in your PowerShell scripts by loading the relevant assemblies into PowerShell (if they aren’t part of the default assembly set) and then using them via New-Object. You can create intricate GUI applications as a front end to your scripts, for instance. Whether you should or not is a discussion for another time.

You can also use .NET code directly in your scripts, which is the topic of this chapter. You’ll see two ways of using .NET directly in your scripts. The first way involves creating a .NET class that you can then use for output or future processing. The second way enables you to create a class with methods you can use in your script to perform an action. You could access the method without creating a class, but ultimately, creating the class gives you more flexibility. Let’s start by looking at how to create a class for output.

.NET class for output

The PowerShell mantra is output objects. Executing a simple piece of PowerShell such as the following produces output onscreen:

PS> Get-CimInstance -ClassName Win32_OperatingSystem |
   select CSName, Caption, OSArchitecture, LastBootUpTime, CountryCode

CSName         : RSLAPTOP01
Caption        : Microsoft Windows 8 Enterprise
OSArchitecture : 32-bit
LastBootUpTime : 17/08/2012 10:02:11
CountryCode    : 44

Output types

.NET class with methods

Summary

About the author