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-NullFunction 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)}现在你可以了Invoke-CommandInTemporaryAppDomain { [Reflection.Assembly]::ReflectionOnlyLoadFrom($args[0]).ImageRuntimeVersion } $myAssemblyPath请注意,我们必须在磁盘上生成一个临时程序集,并让 AppDomain 从那里加载它.这很丑陋,但您不能让 Add-Type 生成内存中的程序集,即使您最终使用 byte[] 加载它在另一个 AppDomain 中是微不足道的,因为您无法在 PowerShell 中挂钩 AppDomain.AssemblyResolve.如果这个命令被打包在一个模块中,你会提前编译包含 ScriptInvoker 的程序集,所以我不认为解决这个问题是优先事项.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. 这篇关于从 Powershell 调用 AppDomain.DoCallback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 16:13