Skip to content

Instantly share code, notes, and snippets.

@ygoe
Created January 29, 2022 23:20
Show Gist options
  • Save ygoe/c0f506f1ac95675c74c7a254f9c908cc to your computer and use it in GitHub Desktop.
Save ygoe/c0f506f1ac95675c74c7a254f9c908cc to your computer and use it in GitHub Desktop.
Write your Windows batch files in C# (using PowerShell)
<# :
@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)
@ygoe
Copy link
Author

ygoe commented Jan 29, 2022

  • Want to write a Windows batch file that can run anywhere without installation?
  • Readable and editable by everyone, without compilation or extra tools (like scriptcs or CS-Script)?
  • CMD is too limited for the job?
  • (Bash would be nice but isn't easily available on Windows?)
  • The PowerShell syntax won't fit in your head?
  • Just use a decent programming language like C#!

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 necessary using 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:

  • No IntelliSense, because you usually won't be using Visual Studio to type this (but you could, and paste in your project code here)
  • No process return codes, because PowerShell doesn't support this without the -File argument which can't be used with a multi-mode file like this
  • Short startup delay (half a second on my old Core i7 3770, but that's for all PowerShell scripts)
  • .NET Framework 4.x by default

To use the latest .NET version (currently .NET 7), install PowerShell 7.x and replace %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe with pwsh.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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment