Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write a class using PowerShell?

Tags:

powershell

With PowerShell being built on top of the .NET framework, can I write my own custom class using PowerShell?

I'm not talking about instantiating .NET classes... that part is plain enough. I want to write my own custom classes using PowerShell scripts. Is it possible? So far my research leads me to say that this isn't possible.

I'm still learning PowerShell, and so far I haven't found an answer on this website, despite a few searches.

like image 210
C Johnson Avatar asked Jul 27 '11 17:07

C Johnson


People also ask

What is the need for a class in PowerShell?

PowerShell classes represent definitions or schemas of those objects. Although you may be familiar with creating objects with commands like New-Object and using the pscustomobject type accelerator, these aren't “new” objects. The kinds of objects these methods produce are of a specific type.

Can you do OOP in PowerShell?

PowerShell is more of an OOP consumer language. It can utilize most of the . NET Framework but it doesn't natively support creating interfaces, classes and certainly not mixins. . NET, which PowerShell's type system is based upon, doesn't support mixins.

Why we use $_ in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.

What does $_ mean in PowerShell?

$_ in the PowerShell is the 'THIS' toke. It refers to the current item in the pipeline. It can be considered as the alias for the automatic variable $PSItem.


1 Answers

Take a look at the Add-Type cmdlet. It lets you write C# and other code in PowerShell. For example (from the above link), in a PowerShell window,

$source = @" public class BasicTest {     public static int Add(int a, int b)     {         return (a + b);     }      public int Multiply(int a, int b)     {         return (a * b);     } } "@  Add-Type -TypeDefinition $source  [BasicTest]::Add(4, 3)  $basicTestObject = New-Object BasicTest $basicTestObject.Multiply(5, 2) 
like image 145
ravikanth Avatar answered Sep 19 '22 03:09

ravikanth