How can I run PowerShell with the .NET 4 runtime?

前端 未结 11 2172
走了就别回头了
走了就别回头了 2020-11-22 07:38

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

11条回答
  •  不思量自难忘°
    2020-11-22 08:00

    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).

提交回复
热议问题