Posts

Showing posts with the label Custom Object

PowerShell Custom Object Formatting

On this article I'm going to touch a field of PowerShell development that most are not aware of. That is formatting. Every PowerShell user has used the "Format-Table" and "Format-List" cmdlets or even the "Format-Custom" to display data in a manner that suits them. What happens though when you have objects that you'll like to format a bit differently or set the default view for? Then its time to use formatting. To start off, we're going to create a custom module. Pick a name for the module - mine is going to be "TestModule" - and create a directory with that name. Then create the module manifest using the "New-ModuleManifest" cmdlet and a script file with the ".psm1" extension. You should end up with a structure like the following: PS C:\> New-Item -ItemType dir -Name TestModule     Directory: C:\Users\cpolydorou\Desktop Mode        LastWriteTime  Length Name ----        -------------  ------ ---- d--...

Powershell Custom Object Formatting

Image
Today I would like to share some guidelines on how to apply formatting to custom powershell objects. There are many times when writing advanced functions, cmdlets and modules where a custom object is very useful, so let's start by creating an object type for our custom objects. Creating a type is very simple, you just define the type as you would in C# and then add it: add-type @' namespace TestModule.CustomObject { public class ExchangeServerMaintenanceMode { public string Name; public bool Enabled; public int ID; } } '@ I should also add here that Powershell 5 makes it even easier by allowing us to create classes directly! Now that we have added the type of our custom object, lets create some objects! $myuser = New-Object TestModule.CustomObject $myuser .Id = "1" $myuser .Name = "User1" $myuser .Enabled = $false Here, we have created a new object of type TestModule.CustomObject and we...