Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to create custom types in Powershell?

Tags:

powershell

Just want to make a simple custom type from [System.Collections.ArrayList] to, say, just shorter[arrayList] or something like that and put it into a module for convenience. Looked into Add-Type but couldn't figure out if it fits and how to do it exactly. What I want to get is:

[ArrayList]<-[System.Collections.ArrayList] #Something like that
$myArList=New-Object ArrayList
$myArList.Add(1,2,3)
like image 964
ephemeris Avatar asked Jan 24 '17 20:01

ephemeris


People also ask

Can you create objects in PowerShell?

You can create objects in PowerShell and use the objects that you create in commands and scripts.

What is a PSObject in PowerShell?

A PSObject is very much like a hashtable where data is stored in key-value pairs. You can create as many key-value pairs as you like for each PSObject .

What is a Noteproperty PowerShell?

NoteProperties are generic properties that are created by Powershell (as opposed to properties that are inherited from a specific dotnet object type).


2 Answers

You're looking for a type accelerator.

[accelerators]::add('arrayList','System.Collections.ArrayList')

I would avoid using non-standard accelerators. PowerShell has good tab completion support for classes since at least v3.

So if you type [arraylTAB then it will complete the full name for you.

Ryan Bemrose brought up a great point; the [accelerators] type accelerator is not available by default, but you can create it like so:

$acc = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$acc::Add('accelerators', $acc)
like image 174
briantist Avatar answered Sep 21 '22 04:09

briantist


If you simply want to avoid re-typing System.Collections.ArrayList all the time, you can simply assign a type literal to a variable and use that:

$ListType = [System.Collections.ArrayList]
$MyArrayList = New-Object $ListType
# more code
$AnotherArrayList = New-Object $ListType

or, using the v5.0 new() constructor:

$MyArrayList = $ListType::new()
like image 33
Mathias R. Jessen Avatar answered Sep 18 '22 04:09

Mathias R. Jessen