That is a slight misunderstanding of creating an instance of an object. When using a .NET type accelerator to create a new instance of that type, you should look at the “new” method of that type to determine what input is required to create a new instance of that class. For the PSCredential class the following should (I’m on my phone, unable to validate) work:
Now, the documentation for the PSCustomObject class does not indicate that a hash table is an acceptable input as a constructor for the class, but I imagine that it may be due to the implementation of that specific type accelerator in PS.
Creating a new PSCustomObject by [PSCustomObject]@{hash table} was introduced in PSv3, but this was specific to that object class, and shouldn’t be confused with constructors for .NET classes and constructors for other object types, which have been around for much longer.
Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"System.Management.Automation.PSCredential".
At line:4 char:26
+ $Creds = [PSCredential]@($UserName, $Password)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
$Obj = [PSCustomObject]@{
foo = "bar"
bar = "bar"}
So I thought I could adopt it and use it with other types/classes than psobject. And finally because I have to review big scripts containing vmware power cli classes and it would make it more readable for me
But like Peter sad, I misunderstood it. I can only create a psobject with a hashtable. If I want to create Object based on other .Net classes I have to use:
$Obj = [PSCredential]@($param1, $param2)
If I get it right, this should use the class constructor with the given params.
CREATE NON-CUSTOM OBJECTS FROM HASH TABLES
You can also use hash tables to create objects for non-custom classes.
When you create an object for a non-custom class, the full namespace
name is required unless class is in the System namespace. Use only the
properties of the class.
For example, the following command creates a session option object.
[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True}
The requirements of the hash table feature, especially the default
constructor requirement, eliminate many existing classes. However,
most Windows PowerShell option classes are designed to work with
this feature, as well as other very useful classes, such as the
ScheduledJobTrigger class.
[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"}
Id Frequency Time DaysOfWeek Enabled
-- --------- ---- ---------- -------
0 Daily 6/6/2012 3:00:00 PM True
One last thing here:
Is there a name or keyword for this approach of interacting with .NET Classes: ` [ClassType]::Method(Params) ` ?