Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Run a .PS1 file without PowerShell

Aug
1,917
68
I came across this article about how to use PowerShell without using PowerShell.

Below is code to run a PowerShell .ps1 file without using PowerShell.

I use CS-Script to run my C# code, but with a few changes to the code, you can use the C# compiler instead.

Code:
//css_args -verbose
//css_autoclass
//css_host /platform:x64
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.IO;
using System;
using System.Text;
namespace PSLess
{
class PSLess
{
   static void Main(string[] args)
   {
     if(args.Length ==0)
         Environment.Exit(1);
     string script=LoadScript(args[0]);
     string s=RunScript(script);
     Console.WriteLine(s);
   }
private static string LoadScript(string filename)
{
   string buffer ="";
   try {
    buffer = File.ReadAllText(filename);
    }
   catch (Exception e)
   {
     Console.WriteLine(e.Message);
     Environment.Exit(2);
    }
  return buffer;
}
private static string RunScript(string script)
{
    Runspace MyRunspace = RunspaceFactory.CreateRunspace();
    MyRunspace.Open();
    Pipeline MyPipeline = MyRunspace.CreatePipeline();
    MyPipeline.Commands.AddScript(script);
    MyPipeline.Commands.Add("Out-String");
    Collection<PSObject> outputs = MyPipeline.Invoke();
    MyRunspace.Close();
   StringBuilder sb = new StringBuilder();
   foreach (PSObject pobject in outputs)
   {
       sb.AppendLine(pobject.ToString());
   }
    return sb.ToString();
  }
}
}

As an example, to run a .PS1 using CS-Script;
Code:
cscs runspace.cs test1.ps1

Even if this is compiled to an .EXE, PSHELL is still a faster solution for TCC.

If/when plugins for TCC can be easily written in C#, this might come in handy.

Joe
 
Back
Top