I am updating a PowerShell script that manages some .NET assemblies. The script was written for assemblies built against .NET 2 (the same version of the framework that Power
Here is the contents of the configuration file I used to support both .NET 2.0 and .NET 4 assemblies:
Also, here’s a simplified version of the PowerShell 1.0 compatible code I used to execute our scripts from the passed in command line arguments:
class Program {
static void Main( string[] args ) {
Console.WriteLine( ".NET " + Environment.Version );
string script = "& " + string.Join( " ", args );
Console.WriteLine( script );
Console.WriteLine( );
// Simple host that sends output to System.Console
PSHost host = new ConsoleHost( this );
Runspace runspace = RunspaceFactory.CreateRunspace( host );
Pipeline pipeline = runspace.CreatePipeline( );
pipeline.Commands.AddScript( script );
try {
runspace.Open( );
IEnumerable output = pipeline.Invoke( );
runspace.Close( );
// ...
}
catch( RuntimeException ex ) {
string psLine = ex.ErrorRecord.InvocationInfo.PositionMessage;
Console.WriteLine( "error : {0}: {1}{2}", ex.GetType( ), ex.Message, psLine );
ExitCode = -1;
}
}
}
In addition to the basic error handling shown above, we also inject a trap
statement into the script to display additional diagnostic information (similar to Jeffrey Snover's Resolve-Error function).