Different behaviour of Powershell Script when run as new process

17 views Asked by At

I have a script that will call a function from a dll. As we have a different version of dependent dlls, we do an AssemblyResolve in the script.

The script looks approximately like this:

$TasksExtensionsDll = [Reflection.Assembly]::LoadFrom("$PSScriptRoot\..\System.Threading.Tasks.Extensions.dll") 
$OnAssemblyResolve = [System.ResolveEventHandler] {
    param($sender, $e)

    Write-Host "Resolving $($e.Name)"
    if ($e.Name -eq "System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51") { 
        # from: System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
        # to:   System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
        return $TasksExtensionsDll 
    }
  
    foreach ($a in [System.AppDomain]::CurrentDomain.GetAssemblies()) {
        if ($a.FullName -eq $e.Name) {
            return $a
        }
    }
    return $null
}
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($OnAssemblyResolve)

try {
    Add-Type -Path "System.Threading.Tasks.Extensions.dll"
    Add-Type -Path "My.Personal.Namespace.dll"
}
catch {
    Write-Host $_.Exception
    Write-Host $_.Exception.LoaderExceptions
}
$output = [My.Personal.Namespace]::MyFunctionCall($somevariables, "$PSScriptRoot\..\SomeFile.xml")

When I run the ps1 file within PowerShell, it works:

PS C:\Test> .\Scripts\test.ps1

But when I run it in a separate process, it fails:

PS C:\Test> powershell.exe -file .\Scripts\test.ps1

Displaying:

powershell.exe : 
At line:1 char:1
+ powershell.exe -file .\Scripts\test.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Process is terminated due to StackOverflowException.

What leads to this behaving differently and how can I resolve this issue, as I will need to run it like this.

0

There are 0 answers