powershell access sibling method - powershell

I'm having trouble accessing sibling methods in powershell
$group.search.has_member(search) is the same once it gets the members, but
$group.retrieve.Members() gets the members differently for 365 groups vs local groups
So I'm trying to have .search.has_member(search) call .retrieve.Members() to minimize code duplication (IRL there's around 15 different versions some with unique retrieval methods, some with shared approaches). But I'm having trouble accessing the sibling's methods
My main goal is I'm trying to build an interface facade that will unify how you interact with Exchange mail objects. 365 mailboxes, local mailboxes, 365 groups, and local groups (among others) all can have Members, MemberOf, Email Addresses and Distinguished Name, but while DN is a property on all objects, Email addresses property is formatted differently on 365 vs local groups (which affects .MatchesSMTP($search)), and retrieving Members() is different for 365 groups vs local groups and should return null for mailboxes and mail contacts regardless of whether it's 365 or local, and retrieval of MemberOf is unique for each object type.
This leads to a significant level of complexity. Originally I was trying to break them out using inheritance based first on Type(mailbox vs group) then on Server(mailbox_365, mailbox_local, etc), but I ended up with too much duplicated code. Same issue when swapping the order (365_mailbox, 365_group, etc).
So now I'm trying to implement abstractions based on behaviors to better share code when possible, and select style/strategy separately for versions that need a more unique approach. But the .Searches are having trouble accessing the .Retrievals.
I guess I could pass the retrievals as a parameter to the searches constructor like I am for config, but that approach doesn't scale well if I start ending up with more behavior categories with interlaced dependencies. Also if I can get the sibling access working I can stop passing config as a parameter and just access them directly, which should clean up the code a bit more.
Below is a reduced example for reference (yes, despite it's complexity it's very reduced, the final version has around 26 classes last time I counted)
Class Mail_Factory
{
static [Mail_Interface] BuildExample1()
{
$mail_object = "Pretend 365 group"
return [Mail_Factory]::Build($mail_object)
}
static [Mail_Interface] BuildExample2()
{
$mail_object = "Pretend Local Group"
return [Mail_Factory]::Build($mail_object)
}
static [Mail_Interface] Build($mail_object)
{
[Mail_Interface] $interface = [Mail_Interface]::new()
$interface.config = [Mail_Config]::new($mail_object)
$interface.retrieve = [Mail_Retrieve]::new($interface.config)
$interface.search = [Mail_Search]::new($interface.config)
[Mail_Retrieve_Members_Style] $members_style = switch ($mail_object)
{
("Pretend 365 group") { [Mail_Retrieve_Members_365Group]::new($interface.config) }
("Pretend Local Group") { [Mail_Retrieve_Members_LocalGroup]::new($interface.config) }
}
# notice that we're setting a specific retreival strategy for "members" depending on object type
$interface.config.members_style = $members_style
return $interface
}
}
Class Mail_Interface
{
Mail_Interface(){}
[Mail_Config] $config
[Mail_Retrieve] $retrieve # This is a facade to unify the way we call different kinds of retreivals (directly from settings, derived from settings, shared based on type, or unique to a specific combination of settings)
[Mail_Search] $search # This is a facade for the same reasons as $retreive
[bool] has_member($search) {return $this.search.has_member($search)}
[object] members() {return #($this.retrieve.members())}
}
Class Mail_Config
{
Mail_Config($mail_object) {$this.mail_object = $mail_object}
[Mail_Retrieve_Members_Style] $members_style # set by factory
[object] $mail_object
}
Class Mail_Retrieve
{
Mail_Retrieve($config){$this.config = $config}
[Mail_Config] $config
[object] Members(){return $this.config.members_style.Members()}
}
Class Mail_Retrieve_Members_Style
{
Mail_Retrieve_Members_Style($config){$this.config = $config}
[Mail_Config] $config
[object] Members(){throw("Syle not yet selected")}
}
Class Mail_Retrieve_Members_365Group : Mail_Retrieve_Members_Style
{
Mail_Retrieve_Members_365Group($config) : base($config) {}
# inherited: [Mail_Config] $config
[object] Members(){return "member of 365 group"}
}
Class Mail_Retrieve_Members_LocalGroup : Mail_Retrieve_Members_Style
{
Mail_Retrieve_Members_LocalGroup($config) : base($config) {}
# inherited: [Mail_Config] $config
[object] Members(){return "member of local group"}
}
Class Mail_Search
{
Mail_Search($config){$this.config = $config}
[Mail_Config] $config
[bool] has_member($search)
{
$members = $this.parent.retrieve.members() # !!! Problem exists here !!!
if ($members -contains "$search") {return $true}
else {return $false}
}
}
function TestExample1()
{
# from
# $a.search.has_member()
# we're trying to access
# $a.retrieve.Members()
$a = [Mail_Factory]::BuildExample1()
$member_a = $a.members()[0]
if ($a.has_member($member_a))
{"Success!"}
else
{"Failed, member match incorrect"}
}
function TestExample2()
{
# from
# $b.search.has_member()
# we're trying to access
# $b.retrieve.Members()
$b = [Mail_Factory]::BuildExample2()
$member_b = $b.members()[0]
$b.has_member($member_b)
if ($b.has_member($member_b))
{"Success!"}
else
{"Failed, member match incorrect"}
}
$result_a = TestExample1
$result_b = TestExample2
$result_a
$result_b
This spits out the following error (I've marked the line with !!! Problem exists here !!!)
You cannot call a method on a null-valued expression.
At line:88 char:9
+ $members = $this.super.retrieve.members() # !!! Problem exist ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
I have full control over this project and currently I'm open to completely refactoring to a different approach if I'm going about this the wrong way. I'm comfortable using chained constructors especially if they improve readability.
And I've been exploring design patterns on G4G, but my experience with them is still neophytic

I ended up replacing the reference to Config with a reference to the parent (Interface). While this opens the possibility of accidental recursion, this appears to be the only way to do it (that I've yet found)
I also flattened the methods, removing .search and .retrieve as they turned out not to be needed for now.
Class Mail_Factory
{
static [Mail_Interface] BuildExample1()
{
$mail_object = "Pretend 365 group"
return [Mail_Factory]::Build($mail_object)
}
static [Mail_Interface] BuildExample2()
{
$mail_object = "Pretend Local Group"
return [Mail_Factory]::Build($mail_object)
}
static [Mail_Interface] Build($mail_object)
{
[Mail_Interface] $interface = [Mail_Interface]::new()
$interface.config = [Mail_Config]::new($mail_object)
#$interface.retrieve = [Mail_Retrieve]::new($interface)
#$interface.search = [Mail_Search]::new($interface)
[Mail_Members_Style] $members_style = switch ($mail_object)
{
("Pretend 365 group") { [Mail_Members_365Group]::new($interface) }
("Pretend Local Group") { [Mail_Members_LocalGroup]::new($interface) }
}
# notice that we're setting a specific retreival strategy for "members" depending on object type
$interface.members_style = $members_style
$interface.has_member_style = [Mail_HasMember_Default]::new($interface)
return $interface
}
}
Class Mail_Interface
{
Mail_Interface(){}
[Mail_Config] $config
# set by factory #
[Mail_HasMember_Style]$has_member_style
[Mail_Members_Style]$members_style
# set by factory #
[bool] HasMember($search) {return $this.has_member_style.HasMember($search)}
[object] members() {return #($this.members_style.Members())}
}
Class Mail_Config
{
Mail_Config($mail_object) {$this.mail_object = $mail_object}
# IRL we store a lot more in here
[object] $mail_object
}
Class Mail_Members_Style
{
Mail_Members_Style($interface){$this.interface = $interface}
[Mail_Interface] $interface
[object] Members(){throw("Syle not yet selected")}
}
Class Mail_Members_365Group : Mail_Members_Style
{
Mail_Members_365Group($interface) : base($interface) {}
# inherited: [Mail_Interface] $interface
[object] Members(){return "member of 365 group"}
}
Class Mail_Members_LocalGroup : Mail_Members_Style
{
Mail_Members_LocalGroup($interface) : base($interface) {}
# inherited: [Mail_Interface] $interface
[object] Members(){return "member of local group"}
}
Class Mail_HasMember_Style
{
Mail_HasMember_Style($interface){$this.interface = $interface}
[Mail_Interface] $interface
[bool] HasMember($search){throw("Syle not yet selected")}
}
Class Mail_HasMember_Default : Mail_HasMember_Style
{
Mail_HasMember_Default($interface) : base($interface) {}
# inherited: [Mail_Interface] $interface
[bool] HasMember($search)
{
$members = $this.interface.members()
if ($members -contains "$search") {return $true}
else {return $false}
}
}
function TestExample1()
{
# from
# $a.has_member_style.has_member()
# we're trying to access
# $a.members_style.Members()
$a = [Mail_Factory]::BuildExample1()
$member_a = $a.members()[0]
if ($a.HasMember($member_a))
{"Success!"}
else
{"Failed, member match incorrect"}
}
function TestExample2()
{
# from
# $b.has_member_style.hasmember()
# we're trying to access
# $b.members_style.Members()
$b = [Mail_Factory]::BuildExample2()
$member_b = $b.members()[0]
if ($b.HasMember($member_b))
{"Success!"}
else
{"Failed, member match incorrect"}
}
function TestExample3()
{
# Verifying HasMember is actually checking stuff
$b = [Mail_Factory]::BuildExample1()
if ($b.HasMember("Not A Member"))
{"Failed, HasMember is incorrectly returning true"}
else
{"Success!"}
}
$result_a = TestExample1
$result_b = TestExample2
$result_c = TestExample2
$result_a
$result_b
$result_c
And the test results
Success!
Success!
Success!

Related

Extending accelerated .Net class using the original constructors

Inspired by theses questions:
Get a specific octet from the string representation of an IPv4
address
Powershell - Checking IP Address range based on CSV file
I am trying to extend the IPAddress class with an ToBigInt() method in PowerShell (if even possible) to be able to easily compare (IPv4 and IPv6) addresses using comparison operations along with -lt and -gt. E.g.:
([IPAddress]'2001:db8::8a2e:370:7334').ToBigInt() -lt ([IPAddress]'2001:db8::8a2e:370:7335').ToBigInt()
My first attempt:
class IPAddress : System.Net.IPAddress {
[Void]ToBigInt() {
$BigInt = [BigInt]0
foreach ($Byte in $This.GetAddressBytes()) {
$BigInt = ($BigInt -shl 8) + $Byte
}
$BigInt
}
}
Causes an error:
Line |
1 | class IPAddress : System.Net.IPAddress {
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Base class 'IPAddress' does not contain a parameterless constructor.
So apparently, I need to add the ([IPAddress]::new) constructors to the sub class:
class IPAddress : System.Net.IPAddress {
IPAddress ([long]$NewAddress) : base($NewAddress) { }
IPAddress ([byte[]]$Address, [long]$ScopeId) : base($Address, $ScopeID) { }
IPAddress ([System.ReadOnlySpan[byte]]$Address, [long]$ScopeId) : base($Address, $ScopeID) { }
IPAddress ([byte[]]$Address) : base($Address) { }
IPAddress ([System.ReadOnlySpan[byte]]$Address) : base($Address) { }
[Void]ToBigInt() {
$BigInt = [BigInt]0
foreach ($Byte in $This.GetAddressBytes()) {
$BigInt = ($BigInt -shl 8) + $Byte
}
$BigInt
}
}
Now, the class defintion is accepted but when I try to create an IPAddress, like:
[IPAddress]'172.13.23.34'
I get a new error:
OperationStopped: Unable to cast object of type 'System.Net.IPAddress' to type 'IPAddress'.
How can I resolve this casting error?

TypeConverter (registration) throws NullRefException in PowerShell

I have a PowerShell class, which I want to automatically be convertable from string.
So I defined a TypeConverter like this:
class StringToAcmeStateConverter : System.Management.Automation.PSTypeConverter {
[bool] CanConvertFrom([object] $object, [Type] $destinationType) {
if($object -is [string]) {
return Test-Path ([string]$object);
}
return $false;
}
[bool] CanConvertTo([object] $object, [Type] $destinationType) {
return $false
}
[object] ConvertFrom([object] $sourceValue, [Type] $destinationType,
[IFormatProvider] $formatProvider, [bool] $ignoreCase)
{
if($null -eq $sourceValue) { return $null; }
if(-not $this.CanConvertFrom($sourceValue, $destinationType)) {
throw [System.InvalidCastException]::new();
}
$paths = [AcmeStatePaths]::new($sourceValue);
return [AcmeDiskPersistedState]::new($paths, $false, $true);
}
[object] ConvertTo([object] $sourceValue, [Type] $destinationType,
[IFormatProvider] $formatProvider, [bool] $ignoreCase)
{
throw [System.NotImplementedException]::new();
}
}
[System.ComponentModel.TypeConverter([StringToAcmeStateConverter])]
<# abstract #> class AcmeState {
AcmeState() {
if ($this.GetType() -eq [AcmeState]) {
throw [System.InvalidOperationException]::new("This is intended to be abstract - inherit To it.");
}
}
<# omitted #>
}
(Full code listing here: https://raw.githubusercontent.com/PKISharp/ACMESharpCore-PowerShell/deep-state/ACME-PS/internal/classes/AcmeState.ps1)
But PowerShell now throws a NullRefException from inside the pipeline.
How would I make PS use the Converter correctly.
Update
Since this question did not contain enough information for a full repro, I created a gist containing the current (failing) code of the module: gist.github.com/glatzert/ba32f291b9155e6d19c29fbe9594a7c5
TypeConversion with PowerShell classes has some non-obvious issues.
My first approach with the TypeConverter-Attribute fails with either an NullRefException or UnknownTypeException (this depends on the order of the classes in your *.ps1).
I dug into the Types.ps1xml and created the following xml:
<Types>
<Type>
<Name>AcmeState</Name>
<TypeConverter>
<TypeName>StringToAcmeStateConverter</TypeName>
</TypeConverter>
</Type>
</Types>
and added TypesToProcess to the .psd1 pointing to the aforementioned ps1xml.
This will fail, stating the Converter is not known, which probably means, that PowerShell will process that file either in another context as the module or prior to loading the module.
To fix that problem, I removed the TypesToProcess from the .psd1 and added Update-TypeData Types.ps1xml as last line to my module, thus it will be run automatically during module import - and voila! This works.
TLDR:
If you want to register a TypeConverter defined in a PowerShell class, you need to use Update-TypeData

Calling AppDomain.DoCallback from Powershell

This is based on the Stack Overflow question: How to load an assembly as reflection-only in a new AppDomain?
I am attempting to determine the runtime version of an assembly, but that assembly could be loaded multiple times as I traverse through nested folders. Loading the assembly directly using
[Reflection.Assembly]::ReflectionOnlyLoadFrom($assembly)
will therefore not work, as the assembly can only be loaded once in the app-domain.
Given the following function to load an assembly in a separate AppDomain:
function Load-AssemblyInNewAppDomain($assembly)
{
Write-Host $assembly.FullName
$domain = [AppDomain]::CreateDomain([Guid]::NewGuid())
$domain.DoCallback
({
$loaded = [Reflection.Assembly]::Load($assembly)
$runtime = $loaded.ImageRuntimeVersion
Write-Host $runtime
})
}
This outputs the contents of the delegate to the console, rather than executing it:
OverloadDefinitions
-------------------
void DoCallBack(System.CrossAppDomainDelegate callBackDelegate)
void _AppDomain.DoCallBack(System.CrossAppDomainDelegate theDelegate)
$loaded = [Reflection.Assembly]::Load($assembly)
$runtime = $loaded.ImageRuntimeVersion
Write-Host $runtime
Note that the results are the same, whether I use PowerShell 4 or 5
Any help/guidance appreciated
First thought: don't muck around with AppDomains at all and use a completely separate process. Those are (relatively) easily launched from PowerShell, at least. The drawback is that it's potentially much slower if you're doing this for lots of files.
$myAssemblyPath = "C:\..."
$getImageRuntimeVersion = {
[Reflection.Assembly]::ReflectionOnlyLoadFrom($input).ImageRuntimeVersion
}
$encodedCommand = [Convert]::ToBase64String(
[Text.Encoding]::Unicode.GetBytes($getImageRuntimeVersion)
)
$imageRuntimeVersion = $myAssemblyPath | powershell -EncodedCommand $encodedCommand
So, is there no way at all to do this with AppDomains in PowerShell? Well, there is, but it's not pretty. You can't use AppDomain.DoCallBack because, as you've discovered, PowerShell can't remote delegates that way (because, under the covers, it produces dynamic methods).
However, it's easy to host the PowerShell runtime, and all PowerShell objects know how to serialize (a requirement for cross-domain remoting), so invoking a PowerShell script in another AppDomain is fairly simple (but still ugly):
$scriptInvokerAssembly = [System.IO.Path]::GetTempFileName() + ".dll"
Add-Type -OutputAssembly $tempAssembly -TypeDefinition #"
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Management.Automation;
public class ScriptInvoker : MarshalByRefObject {
public IEnumerable<PSObject> Invoke(ScriptBlock scriptBlock, PSObject[] parameters) {
using (var powerShell = PowerShell.Create()) {
powerShell.Commands.AddScript(scriptBlock.ToString());
if (parameters != null) {
powerShell.AddParameters(parameters);
}
return powerShell.Invoke();
}
}
}
"#
[Reflection.Assembly]::LoadFile($scriptInvokerAssembly) | Out-Null
Function Invoke-CommandInTemporaryAppDomain([ScriptBlock] $s, [object[]] $arguments) {
$setup = New-Object System.AppDomainSetup
$setup.ApplicationBase = Split-Path ([ScriptInvoker].Assembly.Location) -Parent
$domain = [AppDomain]::CreateDomain([Guid]::NewGuid(), $null, $setup)
$scriptInvoker = $domain.CreateInstanceAndUnwrap(
[ScriptInvoker].Assembly.FullName, [ScriptInvoker]
);
$scriptInvoker.Invoke($s, $arguments)
[AppDomain]::Unload($domain)
}
And now you can do
Invoke-CommandInTemporaryAppDomain {
[Reflection.Assembly]::ReflectionOnlyLoadFrom($args[0]).ImageRuntimeVersion
} $myAssemblyPath
Note that we have to generate a temporary assembly on disk and have AppDomain load it from there. This is ugly, but you can't have Add-Type produce an in-memory assembly, and even if you do end up with a byte[] getting that to load in another AppDomain is anything but trivial because you can't hook AppDomain.AssemblyResolve in PowerShell. If this command was packaged in a module, you'd compile the assembly containing the ScriptInvoker ahead of time, so I don't see working around this as a priority.
You can't run DoCallback via powershell alone. But DoCallBack does work with some inline C#. As Jeroen says it's ugly, but this works:
$assm = "C:\temp\so\bin\dynamic-assembly.dll"
Add-Type -TypeDefinition #"
using System.Reflection;
using System;
namespace Example
{
public class AppDomainUtil
{
public void LoadInAppDomain(AppDomain childDomain, string assemblyName)
{
childDomain.SetData("assemblyName", assemblyName);
childDomain.DoCallBack( new CrossAppDomainDelegate(LoadAssembly)) ;
}
public static void LoadAssembly()
{
string assemblyName = (string)AppDomain.CurrentDomain.GetData("assemblyName");
// console not available from another domain
string log = "c:\\temp\\hello.txt";
System.IO.File.WriteAllText(log, string.Format("Hello from {0}\r\n",AppDomain.CurrentDomain.FriendlyName));
System.IO.File.AppendAllText(log, string.Format("Assembly to load is {0}\r\n",assemblyName));
Assembly loaded = Assembly.Load(assemblyName);
System.IO.File.AppendAllText(log, string.Format("Assemblyloaded: {0}\r\n",loaded.FullName));
}
}
}
"# -OutputAssembly $assm -OutputType Library # must set output assembly otherwise assembly generated in-memory and it will break with Type errors.
Add-Type -Path $assm
function Load-AssemblyInNewAppDomain([string]$assembly) {
Write-Host "Parent domain: $([AppDomain]::CurrentDomain.FriendlyName)"
$util = New-Object Example.AppDomainUtil
$ads = New-Object System.AppDomainSetup
$cd = [AppDomain]::CurrentDomain
# set application base
$ads.ApplicationBase = [IO.path]::GetDirectoryName( $assm )
[System.AppDomain]$newDomain = [System.AppDomain]::CreateDomain([System.Guid]::NewGuid().ToString(), $null, $ads);
Write-Host "Created child domain: $($newDomain.FriendlyName)"
$util.LoadInAppDomain($newDomain, $assembly)
}
Testing it out:
PS C:\WINDOWS\system32> Load-AssemblyInNewAppDomain "".GetType().Assembly.FullName
Parent domain: PowerShell_ISE.exe
Created child domain: 61ab2dbb-8b33-4e7e-84db-5fabfded53aa
PS C:\WINDOWS\system32> cat C:\temp\hello.txt
Hello from 61ab2dbb-8b33-4e7e-84db-5fabfded53aa
Assembly to load is mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Assemblyloaded: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Ability to set CertificateID for LCM with February powershell 5

I'm trying to update my DSC deployment to now use partial configurations to break up the configuration. For that I need to now use a pull process instead of push.
When I try to apply the configuration for the LCM which looks something like:
[DscLocalConfigurationManager()]
Configuration CreateGESService
{
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullorEmpty()]
[PsCredential] $InstallCredential,
[Parameter(Mandatory=$true)]
[ValidateNotNullorEmpty()]
[PsCredential] $RunCredential
)
Node $AllNodes.NodeName
{
$hostVersion = (get-host).Version
# changed how the possible values for debugMode in the February build
if (($hostVersion.Major -ge 5) -and ($hostVersion.Minor -ge 0) -and ($hostVersion.Build -ge 9842)){
$debugMode = 'All'
}
else{
$debugMode = $true
}
#setup the localConfigManager
Settings
{
#CertificateID = $node.Thumbprint
# slower performance - and only available WMF5
# now we need to kill the dsc
DebugMode = $debugMode
ConfigurationMode = 'ApplyAndAutoCorrect'
ConfigurationModeFrequencyMins = '15'
AllowModuleOverwrite = $true
RefreshMode = 'Push'
ConfigurationID = $node.ConfigurationID
}
PartialConfiguration GetEventStoreConfiguration {
Description = "Contains the stuff for GetEventStore Being Installed"
ConfigurationSource = "[ConfigurationRepositoryShare]ConfigSource"
RefreshMode = "Pull"
}
PartialConfiguration ExternalIntegrationConfiguration{
Description = "Contains the stuff for External Integration"
ConfigurationSource = "[ConfigurationRepositoryShare]ConfigSource"
DependsOn = '[PartialConfiguration]GetEventStoreConfiguration'
RefreshMode = "Pull"
}
PartialConfiguration ServeGroupSpike{
Description = "Contains the stuff for External Integration"
ConfigurationSource = "[ConfigurationRepositoryShare]ConfigSource"
DependsOn = '[PartialConfiguration]ExternalIntegrationConfiguration'
RefreshMode = "Pull"
}
ConfigurationRepositoryShare ConfigSource{
SourcePath = "\\someServer\Shared\dscService\Configuration"
Credential = $InstallCredential
}
ResourceRepositoryShare ResourceSource{
SourcePath = "\\someServer\Shared\dscService\Resources"
Credential = $InstallCredential
}
}
If I try to include the CertificateID I get an error like:
The property CertificateID of metaconfiguration is not compatible with the current version 2.0.0 of the configuration
document. This property only works with version greater than or equal to 1.0.0 . In case the version is greater, then
the property MinimumCompatibleVersion should be set to atleast 1.0.0 . Set these properties in the
OMI_ConfigurationDocument instance in the document and try again.
+ CategoryInfo : InvalidArgument: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 4
+ PSComputerName : SGSpike-Main
Naturally when the Configuration is attempted to be applied it can't decrypt the credentials passed, and I get an error in the event view like:
Job {B37D5239-EDBA-11E4-80C2-00155D9ACA1F} :
WarningMessage An error occured while applying the partial configuration [PartialConfiguration]ExternalIntegrationConfiguration. The error message is :
The Local Configuration Manager is not configured with a certificate. Resource '[File]GpgProgram' in configuration 'ExternalIntegrationConfiguration' cannot be processed..
Any ideas how to do this? I had this working with the certificateID when I was using a single configuration in a push model.
Even in the April 2015 drop the problem still seems to exist. Further diagnosis shows that you can:
Not use partial configurations
Not use a certificate to encrypt credentials
Opened an issue on connect (with some more details) at https://connect.microsoft.com/PowerShell/Feedback/Details/1292678

How do I instantiate CorRuntimeHost from mscoree.tlb in PowerShell?

I want to enumerate all the AppDomains in the current process from PowerShell. The process happens to be Visual Studio, which is hosting StudioShell. To do that I need to instantiate CorRuntimHost, which is part of mscoree.tlb, so I can adapt this C# code..
I tried to get the proper name of CorRunTimeHost and pass it to New-Object -COMObject "objectName". Based on this forum posting, I searched the registry and I think the correct name is CLRMetaData.CorRuntimeHost. However, while New-Object -ComObject 'CLRMetaData.CorRuntimeHost' -Strict does return an object, it only exposes the methods intrinsic to a COM object.
Based on this stackoverflow question I tried [Activator]::CreateInstance(). However, the following two statements give me the same problem as New-Object, namely I can't call the ICorRuntimeHost::EnumDomains() method.
$corRuntimeHost = [Activator]::CreateInstance([Type]::GetTypeFromProgID('CLRMetaData.CorRuntimeHost'));
$enumerator = $null;
$corRuntimeHost.EnumDomains([ref]$enumerator);
Method invocation failed because [System.__ComObject] doesn't contain a method named 'EnumDomains'.
At line:1 char:1
+ $corRuntimeHost.EnumDomains([ref]$enumerator)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
To get it working in PowerShell 3.0 I ended up having to use an AssemblyBuilder. Below is the working code:
The problem seems to be that there is no public constructor for mscoree.CorRuntimeHostClass in .NET 4.0 but there is in 3.5.
I later tested this on a Windows 7 VM with powershell 2.0 and now this code will work in PowerShell 2.0 and 3.0.
$tlbName = Split-Path -Parent ([AppDomain]::CurrentDomain.GetAssemblies() | Where { $_.Location -Match '\\mscorlib.dll$' }).Location
$tlbName = Join-Path $tlbName 'mscoree.tlb';
$csharpString = #"
//adapted from here http://blog.semanticsworks.com/2008/04/enumerating-appdomains.html
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
public class ListProcessAppDomains
{
[DllImport( `"oleaut32.dll`", CharSet = CharSet.Unicode, PreserveSig = false )]
private static extern void LoadTypeLibEx
(String strTypeLibName, RegKind regKind,
[MarshalAs( UnmanagedType.Interface )] out Object typeLib);
private enum RegKind
{
Default = 0,
Register = 1,
None = 2
}
private class ConversionEventHandler : ITypeLibImporterNotifySink
{
public void ReportEvent( ImporterEventKind eventKind, int eventCode, string eventMsg )
{
Console.Error.WriteLine("Kind: {0} Code: {1} Message");
}
public Assembly ResolveRef( object typeLib )
{
string stackTrace = System.Environment.StackTrace;
Console.WriteLine("ResolveRef ({0})", typeLib);
Console.WriteLine(stackTrace);
return null;
}
}
public static AssemblyBuilder LoadMsCoreeDll( ref Object typeLib ) {
ConversionEventHandler eventHandler = new ConversionEventHandler();
string assemblyName = "PoshComWrapper.dll";
LoadTypeLibEx( #"$($tlbName)", RegKind.None, out typeLib );
TypeLibConverter typeLibConverter = new TypeLibConverter();
return typeLibConverter.ConvertTypeLibToAssembly( typeLib, assemblyName, 0, eventHandler, null, null, null, null );
}
}
"#
# So we can run this scipt multiple times
try { [ListProcessAppDomains] } catch { Add-Type -TypeDefinition $csharpString }
function Get-AppDomain {
$typeLib = $null;
$assemblyBuilder = [ListProcessAppDomains]::LoadMsCoreeDll([ref] $typeLib)
$corRuntimeHostClass = $assemblyBuilder.CreateInstance('PoshComWrapper.CorRuntimeHostClass')
$enumHandle = [IntPtr]::Zero
$corRuntimeHostClass.EnumDomains([ref] $enumHandle);
$appDomain = $null;
do
{
$corRuntimeHostClass.NextDomain($enumHandle, [ref] $appDomain);
if ($appDomain -ne $null -and $appDomain.GetType() -eq [AppDomain]) { $appDomain; }
} while ($appDomain -ne $null)
}
Get-AppDomain