Powershell Define Powershell Objects
Use PsObject
like this:
$o = new-Object PsObject -property @{Name='donald'; Kind='duck' }
You pass a hashtable as argument for -property
parameter. Also you can create empty object and add properties later:
$o = New-Object PsObject$o | Add-Member NoteProperty project myproj.csproj$o | Add-Member NoteProperty Success $true
You can of course use pipe to Add-Member
$o = New-Object PsObject# ...$o | Add-Member NoteProperty project myproj.csproj -pass | Add-Member NoteProperty Success $true
If I understand the question, you're asking a couple things:
- Can you explicitly specify the type of a variable?
- What type does Powershell use if you don't specify one yourself?
Powershell will certainly let you specify a type explicitly, but it will also infer types. Note that since all types inherit from System.Object
, explicitly specifying [object]
in a combined declaration/assignment statement has no value that I can see. The type system will still infer an appropriate child type. For example:
$x = 3$x.GetType() # Returns 'Int32'Remove-Variable x[object] $x = 3$x.GetType() # Returns 'Int32'Remove-Variable x[valuetype] $x = 3$x.GetType() # Returns 'Int32'Remove-Variable x[int] $x = 3$x.GetType() # Returns 'Int32'
If you split up the declaration and assignment, you can create a variable of type Object
:
Remove-Variable x$x = new-object -TypeName Object$x.GetType() # Returns 'Object'
...but once you assign a value, the variable gets a new inferred type anyway:
$x = 3$x.GetType() # Returns 'Int32'
While the type system will happily infer Int32
when you specify Object
, explicit types win when the inferred type would be incompatible. For example:
$x = 3 # Gets inferred type 'Int32'[string] $x = 3 # Gets explicit type 'String'$x = 'x' # Gets inferred type 'String'[char] $x = 'x' # Gets explicit type 'Char'
If your question is more geared toward defining and using custom object types, Stej's answer is excellent.
Since Powershell 3 one can also parse HashTables to Custom Objects like:
[PSObject] $Piza = [PSCustomObject] @{ Ingredients = 4}
Or if you like to define more detailed types in your object you could use the -AsCustomObject Parameter from New-Module
[PSObject] $Piza = New-Module -AsCustomObject -ScriptBlock { [Guid]$id = [Guid]::NewGuid() [String] $Name = 'Macaroni' Function TestFunction() {} # Dont forget to export your members and functions # as this is built up as a module and stuffed into # an object later Export-ModuleMember -Function * -Variable *}
As there are no things as classes in posh you can add custom classnames and namespaces to your object that you can query later (pseudo instance ;)
$Piza.PSObject.TypeNames.Insert(0, 'Pizas.Macaroni')