Dynamic binary modules

PowerShell Team

Using add-type and import-module you can dynamically compile and load an assembly without any intermediate assembly files to cleanup.

For instance, to run a cmdlet on a remote machine you could send over the cmdlet source code, compile, import, and run it all on the fly.

Let’s say you have your cmdlet called Use-MyCmdlet as C# code in the file mycode.cs:

PS> [string] $code = Get-Content mycode.cs
PS> $s = New-PSSession remoteHost
PS> Invoke-Command $s `
{(Add-Type -TypeDefinition $args[0] -PassThru).assembly | Import-Module} `
-ArgumentList $code
PS> Invoke-Command $s {Use-MyCmdlet}
PS> Remove-PSSession $s

This example gets the C# code as a string and starts a remote session.
It then compiles the code in the remote session with Add-Type and passes the resulting assembly object to import-module.
The cmdlet Use-MyCmdlet is invoked in the remote session which is then removed, with no need to remove any intermediate files on the remote system.

Nigel Sharples [MSFT]


Discussion is closed.

Feedback usabilla icon