PowerShell converts PowerShell scripts to exe

Source: Internet
Author: User


#1, Script Function convert-ps1toexe{    param (    [parameter (Mandatory = $true)]    [validatescript ({$true})]    [validatenotnullorempty ()]        [io. FileInfo] $ScriptFile     )     if ( -not  $ScriptFile. Exists)     {        Write-Warning  "$ScriptFile   Not exits. "         return    }     [ String] $csharpCode  = @ '     using System;    using  system.io;    using system.reflection;    using  system.diagnostics;    namespace loadxmltestconsole    {         public class consolewriter        {             private static void proc_outputdatareceived (object sender,  System.diagnostics.datareceivedeventargs e)              {                 process pro = sender as process;                 console.writeline (E.data);             }             Static void main (String[] args)              {                / / set title of console                 console.title =  "Powered by pstips.net";                  // read script from resource                 assembly ase  = assembly.getexecutingassembly ();                 string scriptname = ase. GetManifestResourceNames () [0];                 string scriptcontent = string. Empty;                using   (stream stream = ase. GetManifestResourceStream (scriptname))                 using  (streamreader reader = new  streamreader (stream))                  {                     scriptcontent = reader. ReadToEnd ();                 }                  string  scriptfile = environment.expandenvironmentvariables (String. Format ("%temp%\\{0}",  scriptname));                 try                 {              & nbsp;     // output script file to temp path                      File.writealltext (scriptfile, scriptcontent);                      ProcessStartInfo proInfo =  New processstartinfo ();                     proInfo.FileName =  "PowerShell.exe";                      proinfo.createnowindow = true;                     proInfo.RedirectStandardOutput = true;                     proinfo.useshellexecute =  false;                     proinfo.arguments = string. Format (" -file {0}", ScriptFile);                      var proc = process.start (ProInfo);                      proc. outputdatareceived += proc_outputdatareceived;                     proc. Beginoutputreadline ();                     proc. WaitForExit ();       &nbsP;             console.writeline ("Hit  Any key to continue ... ");                     console.readkey ();                 }                 catch  (Exception ex)                  {                     console.writeline ("Hit  Exception: {0} ",  ex. Message);                 }                 finally                {                     //  delete temp file                     if  (File.exists (scriptfile))                      {                          file.delete (ScriptFile);                     }                 }              }          }    } ' @     # $ providerdict     $providerDict  = New-Object  ' System.collections.generic.dictionary[[string],[string]]      $providerDict. ADD (' CompilerVersion ', ' v4.0 ')      $codeCompiler  = [microsoft.csharp.csharpcodeprovider ] $providerDict      # create the optional compiler parameters      $compilerParameters  = New-Object  ' System.CodeDom.Compiler.CompilerParameters '      $compilerParameters. generateexecutable  =  $true      $compilerParameters .generateinmemory =  $true       $compilerParameters. warninglevel = 3    $ compilerparameters.treatwarningsaserrors =  $false     $ Compilerparameters.compileroptions =&nbsP; ' /optimize '      $outputExe  = Join-Path  $ScriptFile .directory  "$ ($ scriptfile.basename). exe "     $compilerParameters. outputassembly =  $ outputexe     $compilerParameters. Embeddedresources.add ($ScriptFile. FullName)  >   $null      $compilerParameters. Referencedassemblies.add ( [ System.Diagnostics.Process]. assembly.location )  >  $null      # Compile Assembly      $compilerResult  =  $codeCompiler. CompileAssemblyFromSource ($compilerParameters, $ Csharpcode)      # print compiler errors    if ($ CompilerResult.Errors.HasErrors)     {         write-host  ' Compile faield. see error message as below: '  - Foregroundcolor red         $compilerResult .errors | foreach {             Write-Warning  (' {0},[{1},{2}],{3} '  -f $_. Errornumber,$_. Line,$_. Column,$_. errortext )         }    }     else    {         Write-Host  ' Compile succeed. '  -ForegroundColor Green          "output executable  file to  ' $outputExe ' "    }}2, input convert-ps1toexe -scriptfile .\ Test.ps1

This article is from the "BOM water Year _" blog, please be sure to keep this source http://timefiles.blog.51cto.com/8475652/1794539

PowerShell converts PowerShell scripts to exe

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.