├── .gitignore
├── ALCLoader
├── README.md
├── build.ps1
├── module
│ ├── ALCLoader.psd1
│ └── ALCLoader.psm1
└── src
│ ├── ALCLoader.Shared
│ ├── ALCLoader.Shared.csproj
│ ├── LoadContext.cs
│ └── SharedUtil.cs
│ └── ALCLoader
│ ├── ALCLoader.csproj
│ ├── ConvertToNewtonsoftJsonCommand.cs
│ └── ConvertToYamlDotNetCommand.cs
├── ALCPureScriptModule
├── README.md
├── build.ps1
└── module
│ ├── ALCPureScriptModule.psd1
│ └── ALCPureScriptModule.psm1
├── ALCResolver
├── README.md
├── build.ps1
├── module
│ └── ALCResolver.psd1
└── src
│ ├── ALCResolver.Private
│ ├── ALCResolver.Private.csproj
│ ├── Json.cs
│ ├── SharedUtil.cs
│ └── Yaml.cs
│ └── ALCResolver
│ ├── ALCResolver.csproj
│ ├── ConvertToNewtonsoftJsonCommand.cs
│ ├── ConvertToYamlDotNetCommand.cs
│ └── OnImportAndRemove.cs
├── ALCScriptLoadContext
├── README.md
├── build.ps1
├── module
│ ├── ALCScriptLoadContext.psd1
│ └── ALCScriptLoadContext.psm1
└── src
│ └── ALCScriptLoadContext
│ └── ALCScriptLoadContext.csproj
├── ALCScriptModule
├── README.md
├── build.ps1
├── module
│ ├── ALCScriptModule.psd1
│ └── ALCScriptModule.psm1
└── src
│ └── ALCScriptModule
│ ├── ALCScriptModule.csproj
│ └── LoadContext.cs
├── README.md
├── common.ps1
└── test.ps1
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.vspscc
94 | *.vssscc
95 | .builds
96 | *.pidb
97 | *.svclog
98 | *.scc
99 |
100 | # Chutzpah Test files
101 | _Chutzpah*
102 |
103 | # Visual C++ cache files
104 | ipch/
105 | *.aps
106 | *.ncb
107 | *.opendb
108 | *.opensdf
109 | *.sdf
110 | *.cachefile
111 | *.VC.db
112 | *.VC.VC.opendb
113 |
114 | # Visual Studio profiler
115 | *.psess
116 | *.vsp
117 | *.vspx
118 | *.sap
119 |
120 | # Visual Studio Trace Files
121 | *.e2e
122 |
123 | # TFS 2012 Local Workspace
124 | $tf/
125 |
126 | # Guidance Automation Toolkit
127 | *.gpState
128 |
129 | # ReSharper is a .NET coding add-in
130 | _ReSharper*/
131 | *.[Rr]e[Ss]harper
132 | *.DotSettings.user
133 |
134 | # TeamCity is a build add-in
135 | _TeamCity*
136 |
137 | # DotCover is a Code Coverage Tool
138 | *.dotCover
139 |
140 | # AxoCover is a Code Coverage Tool
141 | .axoCover/*
142 | !.axoCover/settings.json
143 |
144 | # Coverlet is a free, cross platform Code Coverage Tool
145 | coverage*.json
146 | coverage*.xml
147 | coverage*.info
148 |
149 | # Visual Studio code coverage results
150 | *.coverage
151 | *.coveragexml
152 |
153 | # NCrunch
154 | _NCrunch_*
155 | .*crunch*.local.xml
156 | nCrunchTemp_*
157 |
158 | # MightyMoose
159 | *.mm.*
160 | AutoTest.Net/
161 |
162 | # Web workbench (sass)
163 | .sass-cache/
164 |
165 | # Installshield output folder
166 | [Ee]xpress/
167 |
168 | # DocProject is a documentation generator add-in
169 | DocProject/buildhelp/
170 | DocProject/Help/*.HxT
171 | DocProject/Help/*.HxC
172 | DocProject/Help/*.hhc
173 | DocProject/Help/*.hhk
174 | DocProject/Help/*.hhp
175 | DocProject/Help/Html2
176 | DocProject/Help/html
177 |
178 | # Click-Once directory
179 | publish/
180 |
181 | # Publish Web Output
182 | *.[Pp]ublish.xml
183 | *.azurePubxml
184 | # Note: Comment the next line if you want to checkin your web deploy settings,
185 | # but database connection strings (with potential passwords) will be unencrypted
186 | *.pubxml
187 | *.publishproj
188 |
189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
190 | # checkin your Azure Web App publish settings, but sensitive information contained
191 | # in these scripts will be unencrypted
192 | PublishScripts/
193 |
194 | # NuGet Packages
195 | *.nupkg
196 | # NuGet Symbol Packages
197 | *.snupkg
198 | # The packages folder can be ignored because of Package Restore
199 | **/[Pp]ackages/*
200 | # except build/, which is used as an MSBuild target.
201 | !**/[Pp]ackages/build/
202 | # Uncomment if necessary however generally it will be regenerated when needed
203 | #!**/[Pp]ackages/repositories.config
204 | # NuGet v3's project.json files produces more ignorable files
205 | *.nuget.props
206 | *.nuget.targets
207 |
208 | # Microsoft Azure Build Output
209 | csx/
210 | *.build.csdef
211 |
212 | # Microsoft Azure Emulator
213 | ecf/
214 | rcf/
215 |
216 | # Windows Store app package directories and files
217 | AppPackages/
218 | BundleArtifacts/
219 | Package.StoreAssociation.xml
220 | _pkginfo.txt
221 | *.appx
222 | *.appxbundle
223 | *.appxupload
224 |
225 | # Visual Studio cache files
226 | # files ending in .cache can be ignored
227 | *.[Cc]ache
228 | # but keep track of directories ending in .cache
229 | !?*.[Cc]ache/
230 |
231 | # Others
232 | ClientBin/
233 | ~$*
234 | *~
235 | *.dbmdl
236 | *.dbproj.schemaview
237 | *.jfm
238 | *.pfx
239 | *.publishsettings
240 | orleans.codegen.cs
241 |
242 | # Including strong name files can present a security risk
243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
244 | #*.snk
245 |
246 | # Since there are multiple workflows, uncomment next line to ignore bower_components
247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
248 | #bower_components/
249 |
250 | # RIA/Silverlight projects
251 | Generated_Code/
252 |
253 | # Backup & report files from converting an old project file
254 | # to a newer Visual Studio version. Backup files are not needed,
255 | # because we have git ;-)
256 | _UpgradeReport_Files/
257 | Backup*/
258 | UpgradeLog*.XML
259 | UpgradeLog*.htm
260 | ServiceFabricBackup/
261 | *.rptproj.bak
262 |
263 | # SQL Server files
264 | *.mdf
265 | *.ldf
266 | *.ndf
267 |
268 | # Business Intelligence projects
269 | *.rdl.data
270 | *.bim.layout
271 | *.bim_*.settings
272 | *.rptproj.rsuser
273 | *- [Bb]ackup.rdl
274 | *- [Bb]ackup ([0-9]).rdl
275 | *- [Bb]ackup ([0-9][0-9]).rdl
276 |
277 | # Microsoft Fakes
278 | FakesAssemblies/
279 |
280 | # GhostDoc plugin setting file
281 | *.GhostDoc.xml
282 |
283 | # Node.js Tools for Visual Studio
284 | .ntvs_analysis.dat
285 | node_modules/
286 |
287 | # Visual Studio 6 build log
288 | *.plg
289 |
290 | # Visual Studio 6 workspace options file
291 | *.opt
292 |
293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
294 | *.vbw
295 |
296 | # Visual Studio LightSwitch build output
297 | **/*.HTMLClient/GeneratedArtifacts
298 | **/*.DesktopClient/GeneratedArtifacts
299 | **/*.DesktopClient/ModelManifest.xml
300 | **/*.Server/GeneratedArtifacts
301 | **/*.Server/ModelManifest.xml
302 | _Pvt_Extensions
303 |
304 | # Paket dependency manager
305 | .paket/paket.exe
306 | paket-files/
307 |
308 | # FAKE - F# Make
309 | .fake/
310 |
311 | # CodeRush personal settings
312 | .cr/personal
313 |
314 | # Python Tools for Visual Studio (PTVS)
315 | __pycache__/
316 | *.pyc
317 |
318 | # Cake - Uncomment if you are using it
319 | # tools/**
320 | # !tools/packages.config
321 |
322 | # Tabs Studio
323 | *.tss
324 |
325 | # Telerik's JustMock configuration file
326 | *.jmconfig
327 |
328 | # BizTalk build output
329 | *.btp.cs
330 | *.btm.cs
331 | *.odx.cs
332 | *.xsd.cs
333 |
334 | # OpenCover UI analysis results
335 | OpenCover/
336 |
337 | # Azure Stream Analytics local run output
338 | ASALocalRun/
339 |
340 | # MSBuild Binary and Structured Log
341 | *.binlog
342 |
343 | # NVidia Nsight GPU debugger configuration file
344 | *.nvuser
345 |
346 | # MFractors (Xamarin productivity tool) working folder
347 | .mfractor/
348 |
349 | # Local History for Visual Studio
350 | .localhistory/
351 |
352 | # BeatPulse healthcheck temp database
353 | healthchecksdb
354 |
355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
356 | MigrationBackup/
357 |
358 | # Ionide (cross platform F# VS Code tools) working folder
359 | .ionide/
360 |
361 | # Fody - auto-generated XML schema
362 | FodyWeavers.xsd
363 |
364 | ### Custom entries ###
365 | output/
366 | tools/Modules
367 |
--------------------------------------------------------------------------------
/ALCLoader/README.md:
--------------------------------------------------------------------------------
1 | # ALC Loader
2 | This is an example module that uses the `ALC Loader` setup.
3 | The `ALC Loader` example has two assemblies in the module:
4 |
5 | + `ALCLoader.dll`
6 | + Contains the cmdlets and any dep references inside the ALC
7 | + `ALCLoader.Shared.dll`
8 | + Shared code and where the ALC setup code is located
9 |
10 | Some pros and cons using this method over the [ALC Resolver](../ALCResolver/README.md) example are:
11 |
12 | |Pros|Cons|
13 | |-|-|
14 | |Assembly deps can be used by the cmdlet directly|Requires an internal method to support force importing a module a 2nd time|
15 | |No need for an OnImport or OnRemove to cleanup the ALC|Still requires a `.psm1` to load the assembly|
16 | |Can still share data type with the caller using the shared assembly||
17 | |The exact dependency is loaded, it won't use any existing loaded assemblies||
18 |
19 | ## Structure
20 | The module consists of 3 components:
21 |
22 | + PowerShell module [ALCLoader.psd1](./module/ALCLoader.psd1) and [ALCLoader.psm1](./module/ALCLoader.psm1)`
23 | + Shared Assembly util [ALCLoader.Shared](./src/ALCLoader.Shared/)
24 | + Binary module assembly [ALCLoader](./src/ALCLoader/)
25 |
26 | The names of the C# projects used here don't have to be exactly the same, the key part is the `ALCLoader.Shared` contains the `AssemblyLoadContext` setup code and `ALCLoader` contains the cmdlets and code that calls the deps which are contained in the ALC.
27 |
28 | When PowerShell loads `ALCLoader` it will run the code in [ALCLoader.psm1](./module/ALCLoader.psm1) which on PowerShell 7 will create the ALC.
29 | This is done by calling [ALCLoader.Shared.LoadContext](./src/ALCLoader.Shared/LoadContext.cs) to create the ALC, load our binary module, and return the loaded assembly inside that ALC.
30 | Finally the `psm1` will then load the assembly as normal and export the cmdlets within that assembly.
31 |
--------------------------------------------------------------------------------
/ALCLoader/build.ps1:
--------------------------------------------------------------------------------
1 | . $PSScriptRoot/../common.ps1
2 |
3 | Invoke-ModuleBuild -Path $PSScriptRoot
4 |
--------------------------------------------------------------------------------
/ALCLoader/module/ALCLoader.psd1:
--------------------------------------------------------------------------------
1 | @{
2 | RootModule = 'ALCLoader.psm1'
3 | ModuleVersion = '1.0.0'
4 | GUID = '7b99120d-e9cc-4808-a607-871fd42d376c'
5 | Author = 'Jordan Borean'
6 | CompanyName = 'Community'
7 | Copyright = '(c) 2023 Jordan Borean. All rights reserved.'
8 | Description = 'ALC Loader example'
9 | PowerShellVersion = '5.1'
10 | DotNetFrameworkVersion = '4.7.2'
11 | TypesToProcess = @()
12 | FormatsToProcess = @()
13 | NestedModules = @()
14 | FunctionsToExport = @()
15 | CmdletsToExport = @(
16 | 'ConvertTo-NewtonsoftJson'
17 | 'ConvertTo-YamlDotNet'
18 | )
19 | VariablesToExport = @()
20 | AliasesToExport = @()
21 | PrivateData = @{
22 | PSData = @{}
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ALCLoader/module/ALCLoader.psm1:
--------------------------------------------------------------------------------
1 | $importModule = Get-Command -Name Import-Module -Module Microsoft.PowerShell.Core
2 | $moduleName = [System.IO.Path]::GetFileNameWithoutExtension($PSCommandPath)
3 |
4 | if (-not $IsCoreClr) {
5 | # PowerShell 5.1 has no concept of an Assembly Load Context so it will
6 | # just load the module assembly directly.
7 |
8 | # The type can be any type within our ALCLoader project
9 | $innerMod = if ('ALCLoader.ConvertToNewtonsoftJsonCommand' -as [type]) {
10 | $modAssembly = [ALCLoader.ConvertToNewtonsoftJsonCommand].Assembly
11 | &$importModule -Assembly $modAssembly -Force -PassThru
12 | }
13 | else {
14 | $modPath = [System.IO.Path]::Combine($PSScriptRoot, 'bin', 'net472', "$moduleName.dll")
15 | &$importModule -Name $modPath -ErrorAction Stop -PassThru
16 | }
17 | }
18 | else {
19 | # This is used to load the shared assembly in the Default ALC which then sets
20 | # an ALC for the module and any dependencies of that module to be loaded in
21 | # that ALC.
22 |
23 | $isReload = $true
24 | if (-not ('ALCLoader.Shared.LoadContext' -as [type])) {
25 | $isReload = $false
26 |
27 | Add-Type -Path ([System.IO.Path]::Combine($PSScriptRoot, 'bin', 'net5.0', "$moduleName.Shared.dll"))
28 | }
29 |
30 | $mainModule = [ALCLoader.Shared.LoadContext]::Initialize()
31 | $innerMod = &$importModule -Assembly $mainModule -PassThru:$isReload
32 | }
33 |
34 | if ($innerMod) {
35 | # Bug in pwsh, Import-Module in an assembly will pick up a cached instance
36 | # and not call the same path to set the nested module's cmdlets to the
37 | # current module scope. This is only technically needed if someone is
38 | # calling 'Import-Module -Name ALCLoader -Force' a second time. The first
39 | # import is still fine.
40 | # https://github.com/PowerShell/PowerShell/issues/20710
41 | $addExportedCmdlet = [System.Management.Automation.PSModuleInfo].GetMethod(
42 | 'AddExportedCmdlet',
43 | [System.Reflection.BindingFlags]'Instance, NonPublic'
44 | )
45 | foreach ($cmd in $innerMod.ExportedCmdlets.Values) {
46 | $addExportedCmdlet.Invoke($ExecutionContext.SessionState.Module, @(, $cmd))
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/ALCLoader/src/ALCLoader.Shared/ALCLoader.Shared.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net472;net5.0
6 |
7 | 10.0
8 |
9 | enable
10 |
11 |
12 |
13 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ALCLoader/src/ALCLoader.Shared/LoadContext.cs:
--------------------------------------------------------------------------------
1 | // AssemblyLoadContext won't work in net472 so we conditionally compile this
2 | // for net5.0 or greater.
3 | #if NET5_0_OR_GREATER
4 | using System.IO;
5 | using System.Reflection;
6 | using System.Runtime.CompilerServices;
7 | using System.Runtime.Loader;
8 |
9 | namespace ALCLoader.Shared;
10 |
11 | public class LoadContext : AssemblyLoadContext
12 | {
13 | private static LoadContext? _instance;
14 | private static object _sync = new object();
15 |
16 | private Assembly _thisAssembly;
17 | private AssemblyName _thisAssemblyName;
18 | private Assembly _moduleAssembly;
19 | private string _assemblyDir;
20 |
21 | private LoadContext(string mainModulePathAssemblyPath)
22 | : base (name: "ALCLoader", isCollectible: false)
23 | {
24 | _assemblyDir = Path.GetDirectoryName(mainModulePathAssemblyPath) ?? "";
25 | _thisAssembly = typeof(LoadContext).Assembly;
26 | _thisAssemblyName = _thisAssembly.GetName();
27 | _moduleAssembly = LoadFromAssemblyPath(mainModulePathAssemblyPath);
28 | }
29 |
30 | protected override Assembly? Load(AssemblyName assemblyName)
31 | {
32 | // Checks to see if we are trying to access our current assembly
33 | // (ALCLoader.Shared). If so return the already loaded assembly object
34 | // as it provides a common interface between Pwsh and the ALC.
35 | if (AssemblyName.ReferenceMatchesDefinition(_thisAssemblyName, assemblyName))
36 | {
37 | return _thisAssembly;
38 | }
39 |
40 | // Checks to see if the assembly exists in our path, if so load it in
41 | // the ALC. Otherwise fallback to the default loading behaviour.
42 | string asmPath = Path.Join(_assemblyDir, $"{assemblyName.Name}.dll");
43 | if (File.Exists(asmPath))
44 | {
45 | return LoadFromAssemblyPath(asmPath);
46 | }
47 | else
48 | {
49 | return null;
50 | }
51 | }
52 |
53 | public static Assembly Initialize()
54 | {
55 | LoadContext? instance = _instance;
56 | if (instance is not null)
57 | {
58 | return instance._moduleAssembly;
59 | }
60 |
61 | lock (_sync)
62 | {
63 | if (_instance is not null)
64 | {
65 | return _instance._moduleAssembly;
66 | }
67 |
68 | string assemblyPath = typeof(LoadContext).Assembly.Location;
69 | string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);
70 |
71 | // Removes the '.Shared' from the assembly name to refer to our main module.
72 | string moduleName = assemblyName.Substring(0, assemblyName.Length - 7);
73 | string modulePath = Path.Combine(
74 | Path.GetDirectoryName(assemblyPath)!,
75 | $"{moduleName}.dll"
76 | );
77 |
78 | // Creates the ALC which loads our module in the ALC and returns
79 | // the loaded Assembly object for the psm1 to load.
80 | _instance = new LoadContext(modulePath);
81 | return _instance._moduleAssembly;
82 | }
83 | }
84 | }
85 | #endif
86 |
--------------------------------------------------------------------------------
/ALCLoader/src/ALCLoader.Shared/SharedUtil.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Reflection;
4 | #if NET5_0_OR_GREATER
5 | using System.Runtime.Loader;
6 | #endif
7 |
8 | namespace ALCLoader.Shared;
9 |
10 | internal class SharedUtil
11 | {
12 | public static void AddAssemblyInfo(Type type, Dictionary data)
13 | {
14 | Assembly asm = type.Assembly;
15 |
16 | data["Assembly"] = new Dictionary()
17 | {
18 | { "Name", asm.GetName().FullName },
19 | #if NET5_0_OR_GREATER
20 | { "ALC", AssemblyLoadContext.GetLoadContext(asm)?.Name },
21 | #endif
22 | { "Location", asm.Location }
23 | };
24 | }
25 | }
--------------------------------------------------------------------------------
/ALCLoader/src/ALCLoader/ALCLoader.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net472;net5.0
5 | 10.0
6 | true
7 | enable
8 |
9 |
10 |
11 |
16 |
17 |
18 |
19 |
20 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/ALCLoader/src/ALCLoader/ConvertToNewtonsoftJsonCommand.cs:
--------------------------------------------------------------------------------
1 | using ALCLoader.Shared;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Management.Automation;
5 | // We can reference our ALC dependency directly
6 | using Newtonsoft.Json;
7 |
8 | namespace ALCLoader;
9 |
10 | [Cmdlet(VerbsData.ConvertTo, "NewtonsoftJson")]
11 | [OutputType(typeof(string))]
12 | public sealed class ConvertToNewtonsoftJsonCommand : PSCmdlet
13 | {
14 | private List