Can I overload the PowerShell inbuilt class's methods? If yes then how? Any code sample would be great.
Essentially, I am trying to overload the Equals method of a Hashtable Dictionary PowerShell object to do appropriate comparisons.
I know that you can overload a cmdlet or a function in PowerShell and whatever is the latest definition that is taken up. But I am trying to overload not a cmdlet or a function, but trying to overload inbuilt method for existing class. I have already checked this post: Function overloading in PowerShell
Well, you can overload it from C# code in this manner:
$Source = #"
class MyHashTable : HashTable
{
public override Equals(...) { ... }
}
"#
Add-Type -TypeDefinition $Source -Language CSharp
$x = New-Object MyHashTable ...
Related
I need to create a .NET object in PowerShell. The signature for the constructor is:
public ObjCTor(TClient param1, Func<TClient, IInterface> param2)
and the class is defined as:
public class ObjCTor<TClient> : IOtherInt1, IOtherInt2 where TClient : ConcreteBase
The first parameter is easy enough. I'm stumped on the second. How can I pass a PowerShell function as Func<T1, T2>?
UPDATED
PowerShell can convert a ScriptBlock to a delegate, so something like this might work fine:
$sb = { param($t1) $t1 }
New-Object "ObjCTor[CClient, Func[CClient,IInterface]]" -ArgumentList $param1,$sb
Note that PowerShell cannot deduce generic type arguments from a ScriptBlock. In your case, ObjCTor looks like a generic class so type deduction isn't a factor, but if you were calling a generic method, things could get messy.
The syntax supplied by Jason wasn't quiet correct. This works:
$= New-Object "ObjCTor[TClient]" -ArgumentList $param1,$functionToCall
I was also missing the $args[0] as a parameter in my scriptblock/delegate. This is what I should've had:
$functionToCall = { Get-Blah $args[0] }
For example I have a .NET object $m with the following method overloads:
PS C:\Users\Me> $m.GetBody
OverloadDefinitions
-------------------
T GetBody[T]()
T GetBody[T](System.Runtime.Serialization.XmlObjectSerializer serializer)
If I try to invoke the parameterless method I get:
PS C:\Users\Me> $m.GetBody()
Cannot find an overload for "GetBody" and the argument count: "0".
At line:1 char:1
+ $m.GetBody()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
I understand PowerShell v3.0 is supposed to work more easily with generics. Obviously I need to tell it somehow what type I want returned but I cannot figure out the syntax.
It looks like you are trying to invoke a generic method.
In powershell this can be done by:
$nonGenericClass = New-Object NonGenericClass
$method = [NonGenericClass].GetMethod("SimpleGenericMethod")
$gMethod = $method.MakeGenericMethod([string])
# replace [string] with the type you want to use for T.
$gMethod.Invoke($nonGenericClass, "Welcome!")
See this wonderful blog post for more info and additional examples.
For your example you could try:
$Source = #"
public class TestClass
{
public T Test<T>()
{
return default(T);
}
public int X;
}
"#
Add-Type -TypeDefinition $Source -Language CSharp
$obj = New-Object TestClass
$Type = $obj.GetType();
$m = $Type.GetMethod("Test")
$g = new-object system.Guid
$gType = $g.GetType()
$gm = $m.MakeGenericMethod($gType)
$out = $gm.Invoke( $obj, $null)
#$out will be the default GUID (all zeros)
This can be simplified by doing:
$Type.GetMethod("Test").MakeGenericMethod($gType).Invoke( $obj, $null)
This has been testing in powershell 2 and powershell 3.
If you had a more detailed example of how you came across this generic method I would be able to give more details. I have yet to see any microsoft cmdlets return anything that give you generic methods. The only time this comes up is when custom objects or methods from c# or vb.net are used.
To use this without any parameters you can use Invoke with just the first parameter.
$gMethod.Invoke($nonGenericClass)
Calling a generic method on an object instance:
$instance.GetType().GetMethod('MethodName').MakeGenericMethod([TargetType]).Invoke($instance, $parameters)
Calling a static generic method (see also Calling generic static method in PowerShell):
[ClassType].GetMethod('MethodName').MakeGenericMethod([TargetType]).Invoke($null, $parameters)
Note that you will encounter an AmbiguousMatchException when there is also a non-generic version of the method (see How do I distinguish between generic and non generic signatures using GetMethod in .NET?). Use GetMethods() then:
([ClassType].GetMethods() | where {$_.Name -eq "MethodName" -and $_.IsGenericMethod})[0].MakeGenericMethod([TargetType]).Invoke($null, $parameters)
(Mind that there could be more than one method that match the above filter, so make sure to adjust it to find the one you need.)
Hint: You can write complex generic type literals like this (see Generic type of Generic Type in Powershell):
[System.Collections.Generic.Dictionary[int,string[]]]
To call a (parameterless) generic method with overloads from Powershell v3, as shown in the OP example, use the script Invoke-GenericMethod.ps1 from the reference provided by #Chad Carisch, Invoking Generic Methods on Non-Generic Classes in PowerShell.
It should look something like
Invoke-GenericMethod $m GetBody T #()
This is a verified working code sample that I am using:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Practices.ServiceLocation") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Practices.SharePoint.Common") | Out-Null
$serviceLocator = [Microsoft.Practices.SharePoint.Common.ServiceLocation.SharePointServiceLocator]::GetCurrent()
# Want the PowerShell equivalent of the following C#
# config = serviceLocator.GetInstance<IConfigManager>();
# Cannot find an overload for "GetInstance" and the argument count: "0".
#$config = $serviceLocator.GetInstance()
# Exception calling "GetMethod" with "1" argument(s): "Ambiguous match found."
#$config = $serviceLocator.GetType().GetMethod("GetInstance").MakeGenericMethod([IConfigManager]).Invoke($serviceLocator)
# Correct - using Invoke-GenericMethod
$config = C:\Projects\SPG2013\Main\Scripts\Invoke-GenericMethod $serviceLocator GetInstance Microsoft.Practices.SharePoint.Common.Configuration.IConfigManager #()
$config.CanAccessFarmConfig
Here is an alternate script that I haven't tried but is more recent and being actively maintained, Invoke Generic Methods from PowerShell.
Update: PowerShell (Core) 7.3+ now does support calling
generic methods with explicit type arguments.
Note: As of this writing, only preview versions of 7.3 are available.
# PS v7.3+ only; using [string] as an example type argument.
$m.GetBody[string]()
See the conceptual about_Calling_Generic_Methods help topic
PowerShell (Core) 7.2- and Windows PowerShell:
marsze's helpful answer contains great general information about calling generic methods, but let me address the aspect of calling a parameter-less one specifically, as asked:
As hinted at in the question:
in PSv3+ PowerShell can infer the type from the parameter values (arguments) passed to a generic method,
which by definition cannot work with a parameter-less generic method, because there is nothing to infer the type from.
Prior to PowerShell (Core) 7.3, PowerShell previously had no syntax that would allow you to specify the type explicitly in this scenario.
In such older versions, reflection must be used:
# Invoke $m.GetBody[T]() with [T] instantiated with type [decimal]
$m.GetType().GetMethod('GetBody', [type[]] #()).
MakeGenericMethod([decimal]).
Invoke($m, #())
.GetMethod('GetBody', [type[]] #()) unambiguously finds the parameter-less overload of.GetBody(), due to passing in an empty array of parameter types.
.MakeGenericMethod([decimal]) instantiates the method with example type [decimal].
.Invoke($m, #()) then invokes the type-instantiated method on input object ($m) with no arguments (#(), the empty array).
Consider the following PowerShell snippet:
$csharpString = #"
using System;
public sealed class MyClass
{
public MyClass() { }
public override string ToString() {
return "This is my class. There are many others " +
"like it, but this one is mine.";
}
}
"#
Add-Type -TypeDefinition $csharpString;
$myObject = New-Object MyClass
Write-Host $myObject.ToString();
If I run it more than once in the same AppDomain (e.g. run the script twice in powershell.exe or powershell_ise.exe) I get the following error:
Add-Type : Cannot add type. The type name 'MyClass' already exists.
At line:13 char:1
+ Add-Type -TypeDefinition $csharpString;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (MyClass:String) [Add-Type],
Exception
+ FullyQualifiedErrorId :
TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand
How do I wrap the call to Add-Type -TypeDefinition so that its only called once?
This technique works well for me:
if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type)
{
Add-Type -TypeDefinition 'public class MyClass { }'
}
The type name can be enclosed in quotes 'MyClass', square brackets [MyClass], or both '[MyClass]' (v3+ only).
The type name lookup is not case-sensitive.
You must use the full name of the type, unless it is part of the System namespace (e.g. [System.DateTime] can be looked up via 'DateTime', but [System.Reflection.Assembly] cannot be looked up via 'Assembly').
I've only tested this in Win8.1; PowerShell v2, v3, v4.
Internally, the PSTypeName class calls the LanguagePrimitives.ConvertStringToType() method which handles the heavy lifting. It caches the lookup string when successful, so additional lookups are faster.
I have not confirmed whether or not any exceptions are thrown internally as mentioned by x0n and Justin D.
Actually, none of this is required. Add-Type maintains a cache of any code that you submit to it, along with the resulting type. If you call Add-Type twice with the same code, then it won't bother compiling the code and will just return the type from last time.
You can verify this by just running an Add-Type call twice in a row.
The reason you got the error message in the example above is that you changed the code between calls to Add-Type. While the solution above makes that error go away in this situation, it also means that you're working with an older definition of the type that probably isn't acting the way you think it is.
There's a nicer way to do this without incurring the cost of exceptions:
if (-not ("MyClass" -as [type])) {
add-type #"
public class MyClass { }
"#
}
update: well, apparently powershell signals internally with an exception anyway. It has a bad habit of doing this. The interpreter uses SEH to signal with the break and continue keywords, for example.
The simplest way to do this is a try/catch block. You have two options for doing this:
try { [MyClass] | Out-Null } catch { Add-Type -TypeDefinition $csharpString; }
try { Add-Type -TypeDefinition $csharpString; } catch {}
This way no exception is thrown, it's just a little slow base on number of assemblies loaded:
[bool]([appdomain]::CurrentDomain.GetAssemblies() | ? { $_.gettypes() -match 'myclass' })
For example:
function TestThis()
{
[MySpecialCustomAttribute]
[CmdletBinding()]
Param(...)
Process{...}
}
Yes, of course you can!
Any type derived from Attribute which allows UsageType.All (or UsageType.Class) can be used on the function itself (i.e. above Param)
Any type derived from Attribute which allows UsageType.Property or UsageType.Field usage can be used on parameters themselves or variables.
It's not uncommon to just be lazy and use UsageType.All (e.g. the built in OutputType attribute does that).
You can even write them in PowerShell classes now
using namespace System.Management.Automation
class ValidateFileExistsAttribute : ValidateArgumentsAttribute {
[void] Validate([object]$arguments, [EngineIntrinsics]$engineIntrinsics) {
if($null -eq $arguments) {
throw [System.ArgumentNullException]::new()
}
if(-not (Test-Path -Path "$arguments" -Type Leaf)) {
throw [System.IO.FileNotFoundException]::new("The specified path is not a file: '$arguments'")
}
}
}
See more examples on Kevin Marquette's blog.
There's an older example here showing how to do it in PowerShell 4 and earlier using Add-Type, although it's a little out of date now, because the particular example it shows has been integrated into PowerShell 6 and is no longer needed 😉
There are also videos
Code:
add-type #"
public interface IFoo
{
void Foo();
}
public class Bar : IFoo
{
void IFoo.Foo()
{
}
}
"# -Language Csharp
$bar = New-Object Bar
($bar -as [IFoo]).Foo() # ERROR.
Error:
Method invocation failed because [Bar]
doesn't contain a method named 'Foo'.
You can do something like
$bar = New-Object Bar
[IFoo].GetMethod("Foo").Invoke($bar, #())
You get (the reflection representaion of) the member of IFoo from the Type object and call an Invoke overload. Too bad one has to do it that way, though.
Similar approach for explicitly implemented properties etc.
If the method takes arguments, they go in the array #() after the comma in the code above, of course.
I wrote something for PowerShell v2.0 that makes it easy to call explicit interfaces in a natural fashion:
PS> $foo = get-interface $bar ([ifoo])
PS> $foo.Foo()
See:
http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx (archived here).
It does this by generating a dynamic module that thunks calls to the interface. The solution is in pure powershell script (no nasty add-type tricks).
-Oisin
Bad news: It's a bug.
https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=249840&SiteID=99