Created
January 29, 2022 23:20
-
-
Save ygoe/c0f506f1ac95675c74c7a254f9c908cc to your computer and use it in GitHub Desktop.
Write your Windows batch files in C# (using PowerShell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# : | |
@echo off & setlocal & set __args=%* & %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command Invoke-Expression ('. { ' + (Get-Content -LiteralPath ""%~f0"" -Raw) + ' }' + $env:__args) & exit /b %ERRORLEVEL% | |
#> Add-Type @' | |
// ========== BEGIN C# CODE ========== | |
using System; | |
public class App | |
{ | |
public static void Run(string[] args) | |
{ | |
// Write your code here... | |
// Don't forget to add the necessary using statements above. | |
// This is a simple example: | |
Console.WriteLine(".NET version: " + Environment.Version); | |
Console.WriteLine("Arguments: " + string.Join(", ", args)); | |
// Process return codes are not supported by PowerShell with this method. | |
} | |
} | |
// ========== END C# CODE ========== | |
'@; [App]::Run($args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to a few tricks (that I learned from others but forgot the sources) you can inline PowerShell code in a batch file that in turn inlines C# code, all with just 4 lines of boilerplate code, and execute it with the passed command-line arguments. Much like a simple .NET Console application.
Your code goes into the
App.Run
method. You can add more methods and classes if needed. Remember to add the necessaryusing
statements at the top of the code. If you're editing this file in Notepad++, manually select the C# language from the menu to get better syntax highlighting.The only limitations are:
-File
argument which can't be used with a multi-mode file like thisTo use the latest .NET version (currently .NET 7), install PowerShell 7.x and replace
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
withpwsh.exe
at the beginning of the file. The startup delay doubles with the new version. You can verify the version with this C# code:Console.WriteLine(Environment.Version);